假设我想对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
第一个例子中我做错了什么?
当前回答
var arr = [{x:1}, {x:2}, {x:3}];
arr.map(function(a) {return a.x;})
.reduce(function(a, b) {return a + b});
console.log(arr);
//I tried using the following code and the result is the data array
//result = [{x:1}, {x:2}, {x:3}];
var arr2 = [{x:1}, {x:2}, {x:3}]
.reduce((total, thing) => total + thing.x, 0);
console.log(arr2);
// and I changed the code to like this and it worked.
// result = 6
其他回答
只是我对用object literal设置默认值的看法。
让arr = [{ 持续时间:1 },{ 持续时间:3 },{ 持续时间:5 },{ 持续时间:6 }); Const out = arr。Reduce ((a, b) => { 返回{ 持续时间:a.duration + b.duration }; },{ 持续时间:0 }); console.log(出);
我在ES6中做了一点改进:
arr.reduce((a, b) => ({x: a.x + b.x})).x
返回数
我们可以使用数组减少方法来创建新的对象,我们可以使用这个选项来求和或过滤
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)
泛型typescript函数:
const sum = <T>(array: T[], predicate: (value: T, index: number, array: T[]) => number) => {
return array.reduce((acc, value, index, array) => {
return acc + predicate(value, index, array);
}, 0);
};
例子:
const s = sum(arr, (e) => e.x);
//fill创建包含n元素的数组 //reduce需要2个参数,第3个参数作为长度 var fibonacci = (n) =>数组(n).fill()。Reduce ((a, b, c) => { 返回a.concat(c < 2 ?C: a[C - 1] + a[C - 2]) },[]) console.log(斐波纳契(8))