array.prototype.findlast 是 es2023 新增方法,从数组末尾查找首个满足条件的元素;返回 undefined 需判空;chrome 108+ 等现代环境已支持,旧环境可用 reverse().find() 或倒序遍历替代。

Array.prototype.findLast 是 ES2023 新增的方法,专门用于从数组末尾开始查找第一个满足条件的元素(即逻辑上的“最后一个符合条件的元素”)。它非常适合在操作记录(如日志、历史动作列表)中快速定位最近一次发生的特定动作。
基本用法:匹配最后一个“删除”操作
假设你有一组用户操作记录:
const actions = [
{ id: 1, type: 'create', time: '2024-01-01T10:00' },
{ id: 2, type: 'update', time: '2024-01-01T10:05' },
{ id: 3, type: 'delete', time: '2024-01-01T10:10' },
{ id: 4, type: 'update', time: '2024-01-01T10:15' },
{ id: 5, type: 'delete', time: '2024-01-01T10:20' }
];
要找到最后一次 delete 操作,只需:
const lastDelete = actions.findLast(action => action.type === 'delete');
// → { id: 5, type: 'delete', time: '2024-01-01T10:20' }
配合时间字段:找最近 5 分钟内的某个动作
如果记录含时间戳,可结合 Date 判断时效性:
const now = new Date();
const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
<p>const lastRecentUpdate = actions.findLast(action => {
const actionTime = new Date(action.time);
return action.type === 'update' && actionTime >= fiveMinutesAgo;
});</p>处理未匹配情况:返回 undefined,需主动判断
findLast 在找不到时返回 undefined,不能直接解构或读取属性:
- ✅ 安全写法:
if (lastDelete) { console.log(lastDelete.id); } - ❌ 危险写法:
console.log(lastDelete.id); // 报错:Cannot read property 'id' of undefined - ? 可用空值合并:
const id = lastDelete?.id ?? 'none';
兼容性注意:不是所有环境都支持
目前主流现代浏览器(Chrome 108+、Firefox 107+、Safari 16.4+)和 Node.js 18.13+ 已支持。若需兼容旧环境:
- 使用
[...arr].reverse().find(...)(简单但创建新数组,性能略低) - 手动倒序遍历:
for (let i = arr.length - 1; i >= 0; i--) { if (condition(arr[i])) return arr[i]; } - 引入 polyfill(如 core-js)或使用 Lodash 的
findLast










