据我所知,这是一种具有广泛适用性的常用功能.Mozilla开发网络的例子是
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
Run Code Online (Sandbox Code Playgroud)
它具有对值进行求和的效果.当然,这不是一个很好的例子,因为他们不能做到[0, 1, 2, 3, 4].sum().
那么现实生活中的情况是,作为一名网络开发人员,我将面临一个问题并思考," 啊,这是一个工作reduce! "要么是一个非常模糊的情况,要么是一个我可以reduce用作一个常见的情况巧妙的解决方法.
当然,这不是一个很好的例子,因为他们不能做到
[0, 1, 2, 3, 4].sum().
Array#sumJavaScript中没有标准.那就是在那里使用:实现它:
Object.defineProperty(Array.prototype, "sum", {
value: function() {
return this.reduce(function(sum, item) { return sum + item; }, 0);
}
});
Run Code Online (Sandbox Code Playgroud)
(实际上,您可以, 0在此特定示例中关闭该部分;如果您在reduce没有种子值的情况下调用,则它对该回调的第一次调用将第一个条目用作第一个参数,将第二个条目用作secodn.)
或者任何其他类型的累积操作,例如产品,可能使用对象属性:
var foos = [
{foo: 1},
{foo: 2},
{foo: 3}
];
var product = foos.reduce(function(p, obj) {
return p * obj.foo;
}, 0);
Run Code Online (Sandbox Code Playgroud)
或者也许是附加操作:
var list = [
{name: "John"},
{name: "Carla"},
{name: "Mohammed"}
];
var names = list.reduce(function(acc, obj, index) {
if (index === list.length - 1) {
return acc + ", and " + obj.name;
}
return acc + ", " + obj.name;
});
Run Code Online (Sandbox Code Playgroud)
几乎任何涉及积累价值的操作都是我倾向于达到的reduce.
我常常看到的另一种用法(有些人会说滥用)是你想要对数组中的每个项目执行某些操作,包括将其添加到新数组或对象,例如通过对象属性创建数组的交叉索引:
var list = [
{id: 1, name: "John"},
{id: 2, name: "Carla"},
{id: 3, name: "Mohammed"}
];
var index = list.reduce(function(o, item) {
o[item.id] = item;
return o;
}, {});
Run Code Online (Sandbox Code Playgroud)
我上面说"有人会说滥用 " 的原因是上面的累加器(o)实际上并没有改变; 它的状态改变(我们向它添加属性),但它的值没有,因此在这个意义上reduce它没有被用于它的预期目的:建立一个改变的值.但我也经常看到这种用法,可能是因为它让我们index在一个表达式而不是两个表达式中创建.