JavaScript Array findLastIndex()

定义和用法

findLastIndex() 方法为每个数组元素执行一个函数。

findLastIndex() 方法返回通过测试的最后一个元素的索引(位置)。

如果没有找到匹配的元素,findLastIndex() 方法返回 -1。

findLastIndex() 方法不会为空的数组元素执行函数。

findLastIndex() 方法不会改变原始数组。

方法 查找内容
indexOf() 第一个具有指定值的元素的索引。
lastIndexOf() 最后一个具有指定值的元素的索引。
find() 通过测试的第一个元素的值。
findIndex() 通过测试的第一个元素的索引。
findLast() 通过测试的最后一个元素的值。
findLastIndex() 通过测试的最后一个元素的索引。

实例

例子 1

查找最后一个值大于 18 的元素的索引:

const ages = [3, 10, 18, 20];

ages.findLastIndex(checkAge);

function checkAge(age) {
  return age > 18;
}

亲自试一试

例子 2

查找最后一个值大于输入值的元素的索引:

<p><input type="number" id="toCheck" value="18"></p>

<button onclick="myFunction()">Test</button>

<p>Any values above: <span id="demo"></span></p>

<script>
const numbers = [4, 12, 16, 20];

function checkValue(x) {
  return x > document.getElementById("toCheck").value;
}

function myFunction() {
  document.getElementById("demo").innerHTML = numbers.findLastIndex(checkValue);
}
</script>

亲自试一试

语法

array.findLastIndex(function(currentValue, index, arr), thisValue)

参数

参数 描述
function() 必需。为每个数组元素运行的函数。
currentValue 必需。当前元素的值。
index 可选。当前元素的索引。
arr 可选。当前元素所属的数组。
thisValue

可选。传递给函数的 this 值。

默认值为 undefined。

返回值

类型 描述
Number

通过测试的最后一个元素的索引。

如果没有找到,则返回 -1。

浏览器支持

findLastIndex() 是 ES2023 的特性。

自 2023 年 7 月起,所有现代浏览器均支持该方法:

Chrome Edge Firefox Safari Opera
Chrome 110 Edge 110 Firefox 115 Safari 16.4 Opera 96
2023 年 2 月 2023 年 2 月 2023 年 7 月 2023 年 3 月 2023 年 5 月