假设我想对arr中的每个元素求和。
arr = [ { x: 1 }, { x: 2 }, { x: 4 } ];
arr.reduce(function(a, b){ return a.x + b.x; }); // => NaN
我有理由相信a。x在某些时候是没有定义的。
以下工作正常
arr = [ 1, 2, 4 ];
arr.reduce(function(a, b){ return a + b; }); // => 7
第一个例子中我做错了什么?
假设我想对arr中的每个元素求和。
arr = [ { x: 1 }, { x: 2 }, { x: 4 } ];
arr.reduce(function(a, b){ return a.x + b.x; }); // => NaN
我有理由相信a。x在某些时候是没有定义的。
以下工作正常
arr = [ 1, 2, 4 ];
arr.reduce(function(a, b){ return a + b; }); // => 7
第一个例子中我做错了什么?
当前回答
一个更简洁的方法是提供一个初始值作为reduce的第二个参数:
Var arr = [{x:1}, {x:2}, {x:4}]; Var结果= arr。Reduce(函数(acc, obj){返回acc + obj.x;}, 0); console.log(结果);/ / 7
第一次调用匿名函数时,使用(0,{x: 1})调用它,并返回0 + 1 = 1。下一次,它被(1,{x: 2})调用,并返回1 + 2 = 3。然后用(3,{x: 4})调用它,最后返回7。
这也可以处理数组为空的情况,返回0。
其他回答
如果你有一个包含大量数据的复杂对象,比如一个对象数组,你可以采取一步一步的方法来解决这个问题。
如:
const myArray = [{ id: 1, value: 10}, { id: 2, value: 20}];
首先,你应该将你的数组映射到一个你感兴趣的新数组,在这个例子中它可能是一个新的值数组。
const values = myArray.map(obj => obj.value);
这个回调函数将返回一个只包含原始数组中的值的新数组,并将其存储在values const中。现在你的values const是一个这样的数组:
values = [10, 20];
现在你已经准备好执行reduce了:
const sum = values.reduce((accumulator, currentValue) => { return accumulator + currentValue; } , 0);
如您所见,reduce方法多次执行回调函数。对于每一次,它都取数组中该项的当前值,并与累加器相加。为了正确地求和,你需要将累加器的初始值设置为reduce方法的第二个参数。
现在你有了新的const sum值为30。
一个更简洁的方法是提供一个初始值作为reduce的第二个参数:
Var arr = [{x:1}, {x:2}, {x:4}]; Var结果= arr。Reduce(函数(acc, obj){返回acc + obj.x;}, 0); console.log(结果);/ / 7
第一次调用匿名函数时,使用(0,{x: 1})调用它,并返回0 + 1 = 1。下一次,它被(1,{x: 2})调用,并返回1 + 2 = 3。然后用(3,{x: 4})调用它,最后返回7。
这也可以处理数组为空的情况,返回0。
我在ES6中做了一点改进:
arr.reduce((a, b) => ({x: a.x + b.x})).x
返回数
Reduce函数在集合上迭代
arr = [{x:1},{x:2},{x:4}] // is a collection
arr.reduce(function(a,b){return a.x + b.x})
翻译:
arr.reduce(
//for each index in the collection, this callback function is called
function (
a, //a = accumulator ,during each callback , value of accumulator is
passed inside the variable "a"
b, //currentValue , for ex currentValue is {x:1} in 1st callback
currentIndex,
array
) {
return a.x + b.x;
},
accumulator // this is returned at the end of arr.reduce call
//accumulator = returned value i.e return a.x + b.x in each callback.
);
在每次索引回调期间,变量accumulator的值为 在回调函数中传入"a"参数。如果不初始化"accumulator",它的值将是undefined。调用定义。X会给出误差。 要解决这个问题,初始化“accumulator”,值为0,如Casey的答案所示。
为了理解“reduce”函数的输入输出,我建议您查看该函数的源代码。 Lodash库有reduce函数,它的工作原理与ES6中的“reduce”函数完全相同。
以下是链接: 减少源代码
你不应该使用a.x作为累加器,相反,你可以这样做 ' arr = [{x:1},{x:2},{x:4}]
Arr.reduce(函数(a,b){a + b.x},0) '