登录
首页 >  文章 >  前端

如何用 Array.prototype.findLast 查找操作记录中最后一个符合条件的动作

时间:2026-05-04 21:53:43 375浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《如何用 Array.prototype.findLast 查找操作记录中最后一个符合条件的动作》,文章讲解的知识点主要包括,如果你对文章方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

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

如何用 Array.prototype.findLast 查找操作记录中最后一个符合条件的动作

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

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何用 Array.prototype.findLast 查找操作记录中最后一个符合条件的动作》文章吧,也可关注golang学习网公众号了解相关技术文章。

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>