[英]How do I get the sum of the values of a key from array of objects in javascript?
I need to sum all of the values of a key "number" from several objects within an array. 我需要对数组中多个对象的键“数字”的所有值求和。 What would be the correct way to do this?
正确的方法是什么? This is what I've tried.
这就是我尝试过的。
var numarray = [{"number":"10"},{"number":"2"},{"number":"5"},
{"number":"3"},{"number":"21"},{"number":"43"},{"number":"30"}];
function Sum() {
var sum;
for (number in numarray[i]){
alert(sum); //sum would be the result I need to get
}
}
Use forEach to loop through each of the json object. 使用forEach遍历每个json对象。
Use parseInt to convert the values to integer 使用parseInt将值转换为整数
var numarray = [
{"number":"10"},
{"number":"2"},
{"number":"5"},
{"number":"3"},
{"number":"21"},
{"number":"43"},
{"number":"30"}];
function Sum(){
var sum=0;
numarray.forEach(function(item){
sum += parseInt(item.number)
})
document.write('<pre>'+sum+'</pre>')
}
Sum()
EDIT 编辑
When using parseInt it is better to specify the radix 使用parseInt时,最好指定基数
parseInt(item.number,10)
Using a 10 radix means the number is parsed with a base 10 and thus turns the number into the integer .If parseInt
detects a leading zero it will parse the number in octal base 使用10的基数表示该数字以10为底进行解析,从而将数字转换为整数。如果
parseInt
检测到前导零,则将以八进制为基础解析该数字
Using Number 使用号码
Number(item.number)
It will not detect any any octal 它不会检测任何八进制
You can use reduce
for this: 您可以为此使用
reduce
:
Here's how you would normally find the sum of elements in an array: 通常,这是在数组中查找元素总和的方式:
var sum = arr.reduce(function(a,b) {
return a + b;
});
Since you have an array of objects, you'll need to change this to something like: 由于您具有对象数组,因此需要将其更改为以下内容:
var sum = arr.reduce(function(a,b) {
return parseFloat(a) + parseFloat(b.number);
}, 0);
Notice the 0
I've added added as a parameter? 注意到我添加的
0
作为参数添加了吗? It's the default parameter and required in this case. 这是默认参数,在这种情况下是必需参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.