gpt4 book ai didi

javascript - 如何对对象的属性值求和?

转载 作者:行者123 更新时间:2023-12-01 00:36:10 26 4
gpt4 key购买 nike

我想对 PieData 的属性值求和。我的预期输出是25515512+916952499 = 942468011

var PieData = [
{
value: 25515512,
color: "#00a65a",
highlight: "#00a65a",
label: "Received Fund"
},
{
value: 916952499,
color: "#f56954",
highlight: "#f56954",
label: "Pending Fund"
}
];

这是我尝试过的脚本:它打印未定义的值。

var total_value='';
for(var i=0;i<PieData.length;i++){
$.each(PieData[i], function (index, val) {
total_value += val.value;
});
}
alert(total_value);

最佳答案

您可以使用 native 方法 Array#reduce为了它。

var PieData = [{ value: 25515512, color: "#00a65a", highlight: "#00a65a", label: "Received Fund" }, { value: 916952499, color: "#f56954", highlight: "#f56954", label: "Pending Fund" }],
sum = PieData.reduce(function (s, a) {
return s + a.value;
}, 0);

console.log(sum);

ES6

var PieData = [{ value: 25515512, color: "#00a65a", highlight: "#00a65a", label: "Received Fund" }, { value: 916952499, color: "#f56954", highlight: "#f56954", label: "Pending Fund" }],
sum = PieData.reduce((s, a) => s + a.value, 0);

console.log(sum);

关于javascript - 如何对对象的属性值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38540176/

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