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 |
浏览器兼容性
加载中…