gpt4 book ai didi

javascript - 从对象数组中添加属性

转载 作者:行者123 更新时间:2023-12-03 06:39:24 25 4
gpt4 key购买 nike

我正在尝试从对象数组中添加 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

JsFiddle:https://jsfiddle.net/3r8vhfb2/

最佳答案

将其转换为Number

Unary plus (+), The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

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);

或使用 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);

关于javascript - 从对象数组中添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com