我需要得到errorIdx = 3,但我得到 0。如何從陣列的末端回圈遍歷?
const scrollPosition = 5007
const errorsHeight = [947, 2498, 3495, 4805, 5755]
errorIdx = errorsHeight.findIndex((itemHeight: number) => itemHeight < scrollPosition)
console.log(errorIdx) // 0
uj5u.com熱心網友回復:
findLastIndex回呼函式知道thisArg背景關系/目標的另一種實作方式,也將使用它的三個引數呼叫[element, index, array]:因此遵循findIndex...的標準
function findLastIndex(arr, test, target) {
if ((arr ?? true) === true) {
throw new TypeError('findLastIndex called on null or undefined');
};
if (typeof test !== 'function') {
throw new TypeError(`${ test } is not a function`);
};
if (!Array.isArray(arr)) {
arr = Array.from(arr);
}
target = target ?? null;
let isContinue = true;
let idx = arr.length;
// assures -1 as return value for nothing found.
while ((idx >= 0) && isContinue) {
// be aware of sparse array slots ... and ...
// be a guard for the negative index default.
if (arr.hasOwnProperty(--idx)) {
isContinue = !test.call(target, arr[idx], idx, arr);
}
}
return idx;
}
const errorsHeight = [947, 2498, 3495, 4805, 5755];
const scrollPosition = 5007;
console.log(
findLastIndex(errorsHeight, (height/*, idx, arr*/) =>
height < scrollPosition
)
);
console.log(
findLastIndex(errorsHeight, height => height < 5)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
uj5u.com熱心網友回復:
使用陣列或反轉它會為您的解決方案增加額外的 O(n)。
簡單的方法是創建一個輔助函式,從陣列末尾開始查找索引:
function findLastIndex(arr, comparator){
for(let i = arr.length - 1; i > 0; i--){
const valid = comparator(arr[i], i);
if(valid){
return i;
}
}
return -1;
}
console.log(findLastIndex(errorsHeight, (itemHeight: number) => itemHeight < scrollPosition))
uj5u.com熱心網友回復:
最好用一個簡單的 for,像這樣:
const scrollPosition = 5007;
const errorsHeight = [947, 2498, 3495, 4805, 5755];
let errorIdx = -1;
for (let i = 0; i < errorsHeight.length; i )
if((errorIdx === -1 && errorsHeight[i] < scrollPosition) || (errorIdx >= 0 && errorsHeight[i] < scrollPosition && errorsHeight[i] > errorsHeight[errorIdx]))
errorIdx = i;
console.log(errorIdx) //3
;D
uj5u.com熱心網友回復:
您可以通過過濾器保留一組匹配項,然后報告該陣列的長度。我sort在這里添加了一個以確保陣列按數字順序排列。
const scrollPosition = 5007
const errorsHeight = [947, 2498, 3495, 4805, 5755]
errorIdx = errorsHeight
.sort((a, b) => a - b)
.filter(itemHeight => itemHeight < scrollPosition)
.length - 1
console.log(errorIdx)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/405900.html
標籤:
下一篇:列舉并獲取每個元組的第一項?
