我如何使用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