Javascript 如何对json数组求和

Javascript 如何对json数组求和,javascript,jquery,json,Javascript,Jquery,Json,如何使用jQuery对JSON数组中的元素进行如下求和: "taxes": [ { "amount": 25, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI", { "amount": 25, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI", { "amount": 10, "currencyCode": "USD", "decimalPlaces": 0,

如何使用jQuery对JSON数组中的元素进行如下求和:

"taxes": [ { "amount": 25, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI",
{ "amount": 25, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI",
{ "amount": 10, "currencyCode": "USD", "decimalPlaces": 0,"taxCode": "YRI",}],
结果应该是:

totalTaxes=60

使用JSON 101

var foo = {
        taxes: [
            { amount: 25, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"},
            { amount: 25, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"},
            { amount: 10, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"}
        ]
    },
    total = 0,  //set a variable that holds our total
    taxes = foo.taxes,  //reference the element in the "JSON" aka object literal we want
    i;
for (i = 0; i < taxes.length; i++) {  //loop through the array
    total += taxes[i].amount;  //Do the math!
}
console.log(total);  //display the result
var foo={
税款:[
{金额:25,货币代码:“USD”,小数位数:0,税号:“YRI”},
{金额:25,货币代码:“USD”,小数位数:0,税号:“YRI”},
{金额:10,货币代码:“USD”,小数位数:0,税号:“YRI”}
]
},
total=0,//设置一个变量来保存我们的总计
taxes=foo.taxes,//引用我们想要的“JSON”对象文本中的元素
我
对于(i=0;i
如果确实必须使用jQuery,可以执行以下操作:

var totalTaxes = 0;

$.each(taxes, function () {
    totalTaxes += this.amount;
});
或者,您可以在支持ES5
reduce
功能的浏览器中使用该功能:

totalTaxes = taxes.reduce(function (sum, tax) {
    return sum + tax.amount;
}, 0);

或者像@epascarello的答案中那样简单地使用for循环…

10?真正地25 + 25 + 10 = 10? 而且你的JOSN是无效的。@epascarello:显然你没有听说过“新数学”@Louis:你忘记了25个数字中的一个前面的减号。@epascarello结果是以60为基数的。@epascarello在
税[i]上循环有什么问题。
?除了这不是JSON。是一种文本格式。这只是javascript对象和数组表示法。谢谢。我参与了一个冗长的JSON响应。我很抱歉我问题中的错误。但总的来说是这样的