Array.prototype.findLastIndex()
findLastIndex() 方法用於 Array 例項,它會反向遍歷陣列,並返回第一個滿足提供的測試函式的元素索引。如果沒有任何元素滿足測試函式,則返回 -1。
另請參閱 findLast() 方法,該方法返回最後一個滿足測試函式的元素的值(而不是其索引)。
試一試
const array = [5, 12, 50, 130, 44];
const isLargeNumber = (element) => element > 45;
console.log(array.findLastIndex(isLargeNumber));
// Expected output: 3
// Index of element with value: 130
語法
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)
引數
callbackFnthisArg可選-
在執行
callbackFn時用作this的值。請參閱 迭代方法。
返回值
陣列中最後一個(索引最高)透過測試的元素的索引。如果沒有找到匹配的元素,則為 -1。
描述
findLastIndex() 方法是 迭代方法。它會依次為陣列中的每個元素呼叫一次提供的 callbackFn 函式,按照降序索引的順序,直到 callbackFn 返回一個 真值。findLastIndex() 然後返回該元素的索引並停止遍歷陣列。如果 callbackFn 從未返回真值,findLastIndex() 則返回 -1。有關這些方法的一般工作原理,請閱讀 迭代方法 部分。
callbackFn 會為陣列的每一個索引呼叫,而不僅僅是那些有賦值的索引。對於稀疏陣列中的空槽,其行為與 undefined 相同。
findLastIndex() 方法是 通用 的。它只期望 this 值具有 length 屬性和整數鍵屬性。
示例
查詢陣列中最後一個素數的索引
以下示例返回陣列中最後一個素數的索引,如果沒有素數則返回 -1。
function isPrime(n) {
if (n < 2) {
return false;
}
if (n % 2 === 0) {
return n === 2;
}
for (let factor = 3; factor * factor <= n; factor += 2) {
if (n % factor === 0) {
return false;
}
}
return true;
}
console.log([4, 6, 8, 12].findLastIndex(isPrime)); // -1, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLastIndex(isPrime)); // 5
注意:isPrime() 實現僅用於演示。對於實際應用,您需要使用高度記憶化的演算法,例如埃拉託斯特尼篩法,以避免重複計算。
使用 callbackFn 的第三個引數
如果您想訪問陣列中的另一個元素,array 引數就很有用,特別是當您沒有一個現有變數引用該陣列時。以下示例首先使用 filter() 提取正值,然後使用 findLastIndex() 查詢小於其鄰居的最後一個元素。
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const lastTrough = numbers
.filter((num) => num > 0)
.findLastIndex((num, idx, arr) => {
// Without the arr argument, there's no way to easily access the
// intermediate array without saving it to a variable.
if (idx > 0 && num >= arr[idx - 1]) return false;
if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
return true;
});
console.log(lastTrough); // 6
在稀疏陣列上使用 findLastIndex()
您可以在稀疏陣列中搜索 undefined 並獲取空槽的索引。
console.log([1, , 3].findLastIndex((x) => x === undefined)); // 1
在非陣列物件上呼叫 findLastIndex()
findLastIndex() 方法讀取 this 的 length 屬性,然後訪問鍵為小於 length 的非負整數的每個屬性。
const arrayLike = {
length: 3,
0: 2,
1: 7.3,
2: 4,
3: 3, // ignored by findLastIndex() since length is 3
};
console.log(
Array.prototype.findLastIndex.call(arrayLike, (x) => Number.isInteger(x)),
); // 2
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.prototype.findlastindex |
瀏覽器相容性
載入中…