别再使用 .reverse().find():认识 findLast()
If you’ve ever needed to search an array from the end, you’ve probably reached for a combination of .slice().reverse().find(...)
, or looped backward manually. It works, but it’s not an elegant solution.
如果你曾经需要从数组末尾开始搜索,你可能会使用 .slice().reverse().find(...)
的组合,或者手动反向循环。虽然可行,但不够优雅。
We now have a better way: Array.prototype.findLast()
and Array.prototype.findLastIndex()
. These features let you search arrays from the end without reversing them, which gives you cleaner and more intuitive code.
我们现在有了更好的方式:Array.prototype.findLast()
和 Array.prototype.findLastIndex()
。这些特性让你无需反转数组即可从末尾开始搜索,带来更简洁、更直观的代码。
The problem with reversing arrays
反转数组的问题所在
Working with lists in front-end apps (e.g., chat messages, activity logs, form history, etc.) often involves finding the last matching item. Prior to ES2023, you’d typically do something like:
在前端应用中处理列表(例如聊天消息、活动日志、表单历史等)时,通常需要找到 最后一个匹配项。在 ES2023 之前,你通常会这样做:
const lastError = [...logs].reverse().find(log => log.type === 'error');
- Reverses a cloned array, which is inefficient
- 反转克隆后的数组,效率较低
- Risky if you forget to clone (
.slice()
) - 如果忘记克隆(
.slice()
)会有风险 - Less readable and more error-prone
- 可读性更差,更容易出错
Now, you can write:
现在,你可以这样写:
const lastError = logs.findLast(log => log.type === 'error');
- No copying or reversing
- 禁止复制或反转
- Cleaner and clearer
- 更简洁、更清晰
- Safer and more performant, especially with large datasets
- 更安全且性能更高,尤其是在处理大型数据集时
findLast(predicate)
findLast(predicate)
This method works just like .find()
, but starts at the end of the array and moves backward. It takes a predicate, a function that returns true
or false
, for each item.
该方法与 .find()
类似,但从数组末尾开始向前遍历。它接收一个 predicate,即一个为每个元素返回 true
或 false
的函数。
const messages = [ { id: 1, text: 'Hello', read: true }, { id: 2, text: 'Hi', read: false }, { id: 3, text: 'Hey', read: true },
]; const lastUnread = messages.findLast(msg => !msg.read); console.log(lastUnread);
Like .find()
, the predicate receives three arguments: (element, index, array)
:
与 .find()
类似,谓词函数会接收三个参数:(element, index, array)
:
array.findLast((element, index, array) => { })...