添加值数组

时间:2013-07-05 11:58:19

标签: javascript jquery json

这是我的json数据

{
"data" : 
    {
        "Count" : ["1","2","3","4", "5"]

    }

}

如何使用jQuery将结果作为

"Result" : ["1", "3","6","10", "15"]

4 个答案:

答案 0 :(得分:0)

不需要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]));

答案 1 :(得分:0)

除非数据是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);

答案 2 :(得分:0)

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)

答案 3 :(得分:0)

如果你可以使用ECMAScript 5数组方法:假设json是你的json数据......

var sum = 0,
    count = JSON.parse(json).data.Count.map(function(i) {
      return parseInt(i, 10) + sum;
    });