本文介绍了如何求和对象的属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想总结 PieData 的属性值。我的预期产量是
25515512 + 916952499 = 942468011

I want to sum the property values of PieData. My expected output is25515512+916952499 = 942468011

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

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

Here is the script i have tried: It prints undefined value.

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


推荐答案

您可以使用本机方法为它。

You could use the native method Array#reduce for it.

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

这篇关于如何求和对象的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 06:20