我有这个数组:
[
{ id: "1", option { points: "1"} },
{ id: "2", option { points: "20"} },
{ id: "3", option { points: "4"} },
]
我试图对所有具有属性option
的对象points
求和,所以我这样做了:
var total_points = this.my_arr.reduce(function(a, b){
return a + b.option.points;
}, 0);
但是这将返回每个id的索引的连接,例如:012,这当然是错误的。
预期输出为:25
答案 0 :(得分:3)
您必须将字符串转换为数字,例如:
var total_points = this.my_arr.reduce(function(a, b){
return a + parseInt(b.option.points);
}, 0);
答案 1 :(得分:1)
更正您的对象并将b
强制转换为Number
。在对象中,值是字符串,因此当+
与字符串concatenations
一起使用时,不会发生加法运算。这就是将strings
转换为numbers
然后添加的原因
var e=[
{ id: "1", option :{ points: "1"} },
{ id: "2", option :{ points: "20"} },
{ id: "3", option :{ points: "4"} },
]
var total_points = e.reduce(function(a, b){
return a + Number(b.option.points);
}, 0);
console.log(total_points);
答案 2 :(得分:1)
当您使用string
运算符b / w两个+
时,在对象中的选项为strings
,然后将两者合并。使用parseInt()
或Number()
var total_points = this.my_arr.reduce(function(a, b){
return a + parseInt(b.option.points);
}, 0);
答案 3 :(得分:1)
您必须将字符串转换为数字,可以使用parseInt
,或者甚至更简单地在字符串前加上+
。
此版本可用于 NaN ,未定义或缺少属性:
const data = [
{ id: "1", option: { points: "1" } },
{ id: "2", option: { points: "20" } },
{ id: "3", option: { points: "4" } },
{ id: "4", option: { points: NaN } },
{ id: "5", option: { points: undefined } },
{ id: "6", option: { } },
{ id: "7" },
];
const totalPoints = data.reduce((accum, elem) => {
const value = elem.option && elem.option.points ? +elem.option.points : 0;
return accum + value;
}, 0);
console.log(totalPoints);