Array.prototype.findLast 是 ES2023 引入的从数组末尾向前查找首个匹配元素的方法,返回匹配项或 undefined,语义清晰、性能优于 reverse()+find(),适用于获取最新满足条件的记录。

Array.prototype.findLast 是 ES2023 引入的原生方法,专为从数组末尾向前查找第一个匹配项而设计。相比手动 reverse() + find() 或 for 循环倒序遍历,它语义清晰、性能更优(无需创建新数组,且可提前终止),特别适合定位“最新一条”满足条件的业务记录,比如最近一次失败订单、最后一次登录日志、最新有效配置等。
核心用法:传入回调函数,返回首个匹配元素
语法简洁直观:
const item = array.findLast(callback[, thisArg]);
callback 接收三个参数:当前元素、索引、原数组。只要回调返回真值,该元素即被返回并停止搜索。
- 找到则返回对应元素(不是索引);
- 未找到则返回 undefined;
- 空数组直接返回 undefined;
- 不修改原数组,也不新建数组。
典型业务场景示例
假设有一组订单数据,需快速获取「状态为 pending 且创建时间最晚」的那条:
const orders = [
{ id: 1, status: 'success', createdAt: '2024-01-01' },
{ id: 2, status: 'pending', createdAt: '2024-02-10' },
{ id: 3, status: 'pending', createdAt: '2024-03-05' },
{ id: 4, status: 'failed', createdAt: '2024-03-12' }
];
// 从末尾开始找,第一个 status === 'pending' 的就是最新的一条
const latestPending = orders.findLast(order => order.status === 'pending');
// → { id: 3, status: 'pending', createdAt: '2024-03-05' }
与 find / findIndex / reverse+find 的关键区别
- find:从开头找,返回第一个匹配项 —— 不适用于“取最新”逻辑;
- findIndex:只返回索引,还需额外取值,且仍是正向;
- reverse() + find():会新建反转数组,对大数组有内存和性能开销,且破坏原始顺序感知;
- findLast:原地逆向扫描,O(n) 最坏但平均更快(常提前命中),语义即意图。
实用技巧与注意事项
- 支持箭头函数,可结合解构简化判断:
arr.findLast(({ status, amount }) => status === 'refunded' && amount > 100); - 若需同时获取索引,改用 findLastIndex(同属 ES2023);
- 注意兼容性:Chrome 108+、Firefox 107+、Safari 16.4+,旧环境需 polyfill 或降级为 for 循环;
- 对已排序数组(如按时间倒序),findLast 效率接近 O(1) —— 第一个检查项就可能命中。










