在 JavaScript 中,Array.findLastIndex() 方法用于以相反的顺序迭代数组元素,并返回满足所提供函数的最后一个元素的索引。如果没有元素满足提供的函数中的条件,则返回 '-1' 作为结果。
此方法不对空数组元素执行函数。除此之外,此方法不会修改原始数组;相反,它会在新数组中返回结果。
findLastIndex() 方法包含在 ES2023 功能中,并且所有现代浏览器(如 Chrome、Edge、Firefox、Safari 和 Opera)都支持该方法。
语法
以下是 JavaScript Array.findLastIndex() 方法的语法 -
findLastIndex(callbackFn, thisArg)
参数
此方法接受两个参数。下面描述相同 -
- callbackFn −为数组中的每个元素调用的函数。调用此函数时带有三个参数:
- element (可选)−数组中正在处理的当前元素。
- index (可选) −数组中正在处理的当前元素的索引。
- array (可选)−调用数组 findLastIndex()。
- thisArg(可选)-执行 callback 时用作 this 的值。
返回值
此方法返回数组中满足提供的 testing 函数的最后一个元素的索引。如果没有元素满足提供的函数,则将返回 -1。
示例 1
在下面的示例中,我们使用 JavaScript Array.findLastIndex() 方法查找数组中偶数的最后一个索引 -
<html>
<body>
<script>
const numbers = [1, 2, 3, 4, 5, 6];
const lastIndex = numbers.findLastIndex((num) => num % 2 === 0);
document.write(lastIndex);
</script>
</body>
</html>
输出
由于 '6' 是数组中的最后一个偶数,因此将返回其索引号 '5'。
5
示例 2
在此示例中,我们将查找以特定字母 ('a') 开头的字符串的最后一个索引 -
<html>
<body>
<script>
const words = ['apple', 'banana', 'avocado', 'orange', 'grape'];
const lastIndex = words.findLastIndex((word) => word.startsWith('a'));
document.write(lastIndex);
</script>
</body>
</html>
输出
上面的程序返回索引 '2' 作为结果,因为 'avocado' 是满足条件的最后一个单词。
2
示例 3
在这里,我们找到一个大于 10 的元素的最后一个索引 -
<html>
<body>
<script>
const numbers = [5, 8, 12, 15, 20];
const lastIndex = numbers.findLastIndex((num) => num > 10);
document.write(lastIndex);
</script>
</body>
</html>
输出
它返回索引 '4' 作为结果,因为数组中大于 10 的最后一个数字是 '20'。
4
示例 4
在下面的示例中,我们找到一个 '偶数' 的最后一个索引 -
<html>
<body>
<script>
const numbers = [1, 3, 5, 7, 9];
const lastIndex = numbers.findLastIndex((num) => num % 2 === 0);
document.write(lastIndex);
</script>
</body>
</html>
输出
它返回 '-1' 作为结果,因为数组中没有元素满足函数。
-1