假设我想对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
第一个例子中我做错了什么?
当前回答
对于第一次迭代,'a'将是数组中的第一个对象,因此a.x + b.x将返回1+2,即3。
在下一次迭代中返回的3被赋值给a,所以a是一个数字n调用a。x会得到NaN。
简单的解决方法是先将数字映射到数组中,然后将其缩减如下:
arr.map(a=>a.x).reduce(function(a,b){return a+b})
这里arr.map(a=>a.x)将提供一个数字数组[1,2,4],现在使用.reduce(function(a,b){return a+b})将简单地添加这些数字,没有任何麻烦
另一个简单的解决方案是通过将0赋值给a来提供一个初始和为零,如下所示:
arr.reduce(function(a,b){return a + b.x},0)
其他回答
数组缩减函数接受三个参数,即initialValue(默认值) 它是0),累加器和当前值。 默认情况下,initialValue的值为“0”。这是由 蓄电池
让我们用代码来看看。
var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal ) ;
// (remember Initialvalue is 0 by default )
//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks .
// solution = 7
同样的例子还有initial Value:
var initialValue = 10;
var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal,initialValue ) ;
/
// (remember Initialvalue is 0 by default but now it's 10 )
//first iteration** : 10 +1 => Now accumulator =11;
//second iteration** : 11 +2 => Now accumulator =13;
//third iteration** : 13 + 4 => Now accumulator = 17;
No more array properties now the loop breaks .
//solution=17
同样适用于对象数组(当前的stackoverflow问题):
var arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(acc,currVal){return acc + currVal.x})
// destructing {x:1} = currVal;
Now currVal is object which have all the object properties .So now
currVal.x=>1
//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks
//solution=7
要记住的一件事是InitialValue默认为0,可以给任何我的意思{},[]和数字
你不应该使用a.x作为累加器,相反,你可以这样做 ' arr = [{x:1},{x:2},{x:4}]
Arr.reduce(函数(a,b){a + b.x},0) '
您可以使用减少方法如下所示;如果您将0(零)更改为1或其他数字,它会将其添加到总数中。例如,这个例子给出的总数是31,但是如果我们把0改为1,总数将是32。
const batteryBatches = [4, 5, 3, 4, 4, 6, 5];
let totalBatteries= batteryBatches.reduce((acc,val) => acc + val ,0)
我们可以使用数组减少方法来创建新的对象,我们可以使用这个选项来求和或过滤
const FRUITS = ["apple", "orange"] const fruitBasket ={香蕉:{数量:10,kg:3},苹果:{数量:30,kg:10},橙子:{数量:1,kg:3}} const newFruitBasket =水果。Reduce ((acc, fruit) =>({…acc, [fruit]: fruitBasket[fruit]}), {}) console.log (newFruitBasket)
let temp =[{x:1},
{x:2},
{x:3},
{x:4}];
let sum = temp.map(element => element.x).reduce((a, b) => a+ b , 0)
console.log(sum);
我们可以用这种方法求x的和
输出:10