【问题标题】:Why ES6 has 'find' method as its functionality can be achieved through 'reduce'?为什么 ES6 有 'find' 方法,因为它的功能可以通过 'reduce' 来实现?
【发布时间】:2018-03-30 06:18:21
【问题描述】:

在 javascript 中,我们遇到了一个阶段,我们希望根据键从对象数组中获取对象(如果我们不在 Backbone 集合的上下文中工作)。

较新版本的javascript有find方法直接完成上述操作。

但也可以通过 es5 中的 reduce 方法实现。

【问题讨论】:

  • 如果有reduce() 方法,那还有find() 方法吗?如果您可以遍历数组,为什么还有reduce() 方法?如果您可以将所有内容都放在字节缓冲区中,为什么还有一个数组?

标签: ecmascript-6 find reduce


【解决方案1】:

引入.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 变得更加不可读了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多