JavaScript 数组 findLastIndex()
示例 1
查找值大于 18 的最后一个元素
const ages = [3, 10, 18, 20];
ages.findLastIndex(checkAge);
function checkAge(age) {
return age > 18;
}
自己动手试一试 »
描述
findLastIndex()
方法为数组中的每个元素执行一个函数。
findLastIndex()
方法返回通过测试的最后一个元素的索引(位置)。
如果没有找到匹配项,findLastIndex()
方法返回 -1。
findLastIndex()
方法不会对空数组元素执行函数。
findLastIndex()
方法不会更改原始数组。
数组查找方法
方法 | 查找 |
---|---|
indexOf() | 具有指定值的第一个元素的索引 |
lastIndexOf() | 具有指定值的最后一个元素的索引 |
find() | 通过测试的第一个元素的值 |
findIndex() | 通过测试的第一个元素的索引 |
findLast() | 通过测试的最后一个元素的值 |
findLastIndex() | 通过测试的最后一个元素的索引 |
语法
array.findLastIndex(function(currentValue, index, arr), thisValue)
参数
参数 | 描述 |
function() | 必需。 为每个数组元素运行的函数。 |
currentValue | 必需。 当前元素的值。 |
index | 可选。 当前元素的索引。 |
arr | 可选。 当前元素所属的数组。 |
thisValue | 可选。默认 undefined 。作为其 this 值传递给函数的值。 |
返回值
类型 | 描述 |
Number | 通过测试的最后一个元素的索引。 否则返回 -1。 |
更多示例
查找值大于输入值的最后一个元素
<p><input type="number" id="toCheck" value="18"></p>
<button onclick="myFunction()">测试</button>
<p>大于以下值的任何值:<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>
自己动手试一试 »
浏览器支持
findLastIndex()
是 ES2023 的一个特性。
自 2023 年 7 月起,所有现代浏览器均支持此功能。
Chrome 110 | Edge 110 | Firefox 115 | Safari 16.4 | Opera 96 |
2023 年 2 月 | 2023 年 2 月 | 2023 年 7 月 | 2023 年 3 月 | 2023 年 5 月 |