array.prototype.findlastindex 是 es2023 新增方法,从数组末尾向开头查找首个满足条件元素的索引,未找到返回-1;语法为 arr.findlastindex(callback, thisarg),与 findindex 行为相反但签名一致。

Array.prototype.findLastIndex 是 ES2023 引入的方法,专门用于从数组末尾(右向左)查找第一个满足条件的元素索引。它不会修改原数组,返回匹配项的索引;若没找到,返回 -1。
基本用法和参数说明
语法:arr.findLastIndex(callback(element[, index[, array]])[, thisArg])
参数含义:
-
callback:必需,每次遍历执行的函数,接收三个参数:
element(当前元素)、index(当前索引)、array(原数组) -
thisArg:可选,指定回调函数中
this的值
和 findIndex 的关键区别
两者签名一致,但行为相反:
-
findIndex从左到右,返回第一个匹配项的索引(最小索引) -
findLastIndex从右到左,返回最后一个匹配项的索引(最大索引)
例如:[1, 2, 3, 2, 4].findIndex(x => x === 2) → 1[1, 2, 3, 2, 4].findLastIndex(x => x === 2) → 3
实际使用示例
常见场景包括找最后一个偶数、最后一个包含某字符的字符串、或最后一个满足业务条件的对象索引:
- 找最后一个负数:
[-5, 3, -2, 7, -1].findLastIndex(x => x → <code>4 - 找最后一个长度大于 3 的字符串:
['a', 'hello', 'hi', 'world'].findLastIndex(s => s.length > 3)→3 - 找最后一个 status 为 'done' 的对象索引:
list.findLastIndex(item => item.status === 'done')
兼容性与降级方案
目前主流浏览器(Chrome 110+、Firefox 111+、Safari 16.4+)已支持。如需兼容旧环境,可用以下简单 polyfill:
if (!Array.prototype.findLastIndex) {<br> Array.prototype.findLastIndex = function(callback, thisArg) {<br> for (let i = this.length - 1; i >= 0; i--) {<br> if (callback.call(thisArg, this[i], i, this)) return i;<br> }<br> return -1;<br> };<br>}
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











