我有一个对象数组,我正在尝试对数组中的所有num
求和。该数组如下所示:
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
所以总和应该是7。
如何计算Javascript中的总数?
我试过了:
var sum = arr.reduce(function(a, b) {
return a + b;
});
但是这会回来:
"[object Object][object Object][object Object]"
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
答案 0 :(得分:4)
听起来您想将一组值减少为单个值。使用reduce
:
var a = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
a.reduce(function(prev, curr) { return prev + curr.num }, 0);
7
reduce
遍历数组的每个元素,并使用您传递的函数累积值。最后一个参数是prev
的初始值。
自2011年起,这只“仅”出现在ECMAScript Language specification中,因此如果您需要支持旧版浏览器,您可能会尝试underscore.js之类的内容:
_.reduce(a, function(prev, curr) { return prev + curr.num }, 0);
如果存在这样的事情,这将回归到本机实现。
或者如果您想自己动手,可以使用循环:
for (var i = 0, sum = 0; i < a.length; ++i) {
sum += a[i].num;
}
答案 1 :(得分:3)
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = 0;
for(var i = 0; i < arr.length; i++) {
sum = sum + arr[i].num;
}
答案 2 :(得分:1)
应该这样做......
function getSum(theArray){
var sum = 0;
for(var i = 0; i<theArray.length; i++){
var sum += theArray[i].num
}
return sum;
}
答案 3 :(得分:1)
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = 0;
arr.forEach(function(obj){
sum += obj.num;
});
//now sum have 7
console.log(sum);
答案 4 :(得分:1)
您可以使用Array.prototype.map将其转换为数字数组,然后Array.prototype.reduce将它们相加:
var array = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = array.map(function (a) {
return a.num;
}).reduce(function (a, b) {
return a + b;
});
答案 5 :(得分:0)
你只需要遍历数组并增加一个变量:
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = 0;
for(var obj in arr) {
sum += arr[obj].num;
}
// sum now contains the value 7