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() 方法不会更改原始数组。
数组查找方法:
| 方法 | 查找 |
|---|---|
| includes() | 如果数组包含指定值,则返回 true |
| 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()">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>亲自试一试 »浏览器支持
findLastIndex() 是 JavaScript 2023 的一项特性。
ES 2023 自 2023 年 7 月起,所有现代浏览器均已支持 ES 2023。
| Chrome 110 |
Edge 110 |
Firefox 115 |
Safari 16.4 |
Opera 96 |
| 2023年2月 | 2023年2月 | 2023年7月 | 2023年3月 | 2023年5月 |
