在算术运算变量后得到NaN

时间:2013-12-27 10:40:37

标签: javascript jquery json

我正在对数组执行算术运算,这是通过JSON从响应中获得的。 但我不知道为什么我在加入后会得到NaN。

var a = new Array();
var b = 0;
var c = 0;
alert(b);
for (var x = 0; x < length; x++) {
    a[x] = response.data[x]
}
for (var i = 0; i < length; i++) {
    alert('value of b: ' + b); //first time 0 than NaN
    c = a[i];
    a[i] = a[i] - b;
    chart.addSeries(response.legend + "-" + i, a[i], {
        color: colorArray[i]
    }); //performing DOJO chart functioning
    b = b + a[i];
    console.log(b);
    alert('value of a: ' + a[i]); // here  value comes NaN              
}

在上面的代码中,response.data表示包含图表数据的JSONArray。这就是获得NaN的原因。

JSON:

{
    "legend": 5,
    "data": [
        [
            {
                "text": "June",
                "value": 6,
                "customerID": "RITL00002",
                "y": 0
            },
            {
                "‌​text": "July",
                "value": 7,
                "customerID": "RITL00002",
                "y": 0
            },
            {
                "text": "Auguest",
                "value": 8,
                "customerID": "RITL00002",
                "y": 0
            },
            {
                "text": "September",
                "value": 9,
                "customerID": "RIT‌​L00002",
                "y": 0
            },
            {
                "text": "October",
                "value": 10,
                "customerID": "RITL00002",
                "y": 41995.52
            },
            {
                "text": "November",
                "value": 11,
                "customerID": "RITL00002",
                "y": 566353.8099999999
            },
            {
                "text": "December",
                "value": 12,
                "customerID": "RITL00002",
                "y": 0
            }
        ]
    ],
    "Success": true,
    "da‌​taLength": 1
}

1 个答案:

答案 0 :(得分:1)

考虑到您要保存数组"y"中数据"a"的值

要访问"y",您需要获取response.data[0][x].y的值。

所以你的最终代码看起来像

var a = new Array();
var b = 0;
var c = 0;
alert(b);
for (var x = 0; x < length; x++) {
    a[x] = response.data[0][x].y;
}
for (var i = 0; i < length; i++) {
    alert('value of b: ' + b); //first time 0 than NaN
    c = a[i];
    a[i] = a[i] - b;
    chart.addSeries(response.legend + "-" + i, a[i], {
        color: colorArray[i]
    }); //performing DOJO chart functioning
    b = b + a[i];
    console.log(b);
    alert('value of a: ' + a[i]); // here  value comes NaN              
}

如果你想要别的东西,请告诉我。

检查小提琴here