如何总结JSON数组
问题描述:
如何可以总结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,"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
答
如果你真的必须使用jQu ERY,你可以这样做:
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 2012-04-19 03:59:29
几个无与伦比的'{单曲 – kev 2012-04-19 04:01:06
@epascarello:显然,你有没有听说过“新数学” – sberry 2012-04-19 04:02:03