这是我拥有的 json 数据
{
"data" :
{
"Count" : ["1","2","3","4", "5"]
}
}
我如何使用 jQuery 来获得结果
"Result" : ["1", "3","6","10", "15"]
这是我拥有的 json 数据
{
"data" :
{
"Count" : ["1","2","3","4", "5"]
}
}
我如何使用 jQuery 来获得结果
"Result" : ["1", "3","6","10", "15"]
如果您可以使用 ECMAScript 5 Array 方法:假设json
是您的 json 数据...
var sum = 0,
count = JSON.parse(json).data.Count.map(function(i) {
return parseInt(i, 10) + sum;
});
var myArray = [];
var data = myArray.data
for ( var i = 0; i < data.length; i = i + 1 ) {
val = i == 0 ? 0 : myArray[i-1]
myArray.push(data[i]+val)
}
console.log(myArray)
除非数据是 DOM 对象的一部分,否则我看不到使用 jQuery 的意义。
var myData =
{
"data" :
{
"Count" : ["1","2","3","4", "5"]
}
}
var countAry = myData.data.Count;
var results = new Array(countAry.length);
for (var i = 0, il = countAry.length; i < il; i++) {
results[i] = Number(countAry[i]) + (results[i - 1] || 0);
}
myData.data.Results = results;
console.log(myData);
不需要 jQuery,一个原始循环就可以做到这一点:
// Either
var obj = {"data":{"Count":["1","2","3","4","5"]}}
// or
var obj = JSON.parse(jsonString);
var arr = obj.data.Count,
res = [],
acc = 0;
for (var i=0; i<arr.length; i++)
res[i] = String(acc += Number(arr[i]));
obj.data.Result = res;
或者,如果您只想将计数添加到之前的(单个)计数中,请使用
for (var i=0; i<arr.length; i++)
res[i] = String(+arr[i] + (i && +arr[i-1]));