我正在尝试从对象数组中添加ID属性。显示的结果是01395 - 相反,它应该是27 (因为那是13 + 9 + 5等于)。
我认为代码是连接ID属性而不是添加它们的期望结果。
var collection = [{
"Name": "Charlie",
"ID": "13"
}, {
"Name": "Emma",
"ID": "9"
}, {
"Name": "Bob",
"ID": "5"
}];
total = 0, //set a variable that holds our total
id = collection, //reference the element in the "JSON" aka object literal we want
i = 0;
for (i = 0; i < id.length; i++) { //loop through the array
total += id[i].ID; //Do the math!
}
console.log(total); //display the result
&#13;
JsFiddle:https://jsfiddle.net/3r8vhfb2/
答案 0 :(得分:1)
将其转换为Number
Unary plus (+)
,unary plus operator
位于其操作数之前,并计算其操作数,但尝试将其转换为number
,如果它还没有。
var collection = [{
"Name": "Charlie",
"ID": "13"
}, {
"Name": "Emma",
"ID": "9"
}, {
"Name": "Bob",
"ID": "5"
}];
var total = 0,
id = collection;
for (var i = 0; i < id.length; i++) {
total += +id[i].ID;
//OR total += Number(id[i].ID);
}
console.log(total);
&#13;
或使用 Array#reduce
:
var collection = [{
"Name": "Charlie",
"ID": "13"
}, {
"Name": "Emma",
"ID": "9"
}, {
"Name": "Bob",
"ID": "5"
}];
var total = collection.reduce(function(a, b) {
return +(a.ID || a) + +(b.ID);
});
console.log(total);
&#13;