引入.find() 的最可能原因是它是一个非常普遍需要的功能。以下面的代码为例:
let arr = [{id: 1, descriptor: "firstElement"}, {id: 2}, {id: 3}, {id: 1, descriptor: "lastElement"}];
// find using reduce
let foundItem = arr.reduce((prevItem, item) => item.id === 1 ? item : prevItem, arr);
// find using find
let foundItem2 = arr.find(item => item.id === 1);
console.log(foundItem); // prints: {id: 1, descriptor: "lastElement"}
console.log(foundItem2); // prints: {id: 1, descriptor: "firstElement"}
使用.find() 的代码更简洁易读。此外,.find() 准确地表达了你想在这里做的事情:“找到与表达式匹配的第一个项目”,而 .reduce() 只表达“将数组减少到一个项目,但是看起来可能”。您必须阅读表达式以确定 reduce 正在做什么。这对于查找东西等常见功能来说很麻烦。
另一个区别:.find() 在找到第一个元素后停止并返回第一个元素。 reduce() 方法不会停止,并且在我实现它时,它将返回数组中的最后一个匹配元素。如果你想要第一个,reduce 应该是这样的:
let arr = [{id: 1, descriptor: "firstElement"}, {id: 2}, {id: 3}, {id: 1, descriptor: "lastElement"}];
let foundItem = arr.reduce((prevItem, item) => prevItem.id === 1 ? prevItem : item.id === 1 ? item : prevItem, arr);
现在 reduce 变得更加不可读了。