Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

javascript - Object returning NaN when sum values

I'll admit I'm weak in JavaScript and JSON. I've spent a lot of time attempting to figure out why numbers from my objects returns NaN when they are added together. With that in mind, below is my JSON, stored to a variable:

var data = [
    {
        "acc_ext_id": null,
        "cat_code": 10002,
        "cat_ds": "REVENUE",
        "category_id": null,
        "chart_id": null,
        "created_at": null,
        "dept_id": null,
        "feb": null,
        "id": null,
        "jan": 30,
        "note": null,
        "total_cost": null,
        "updated_at": null,
        "year_id": null
    },
    {
        "acc_ext_id": "41260-02600",
        "cat_code": 10002,
        "cat_ds": "REVENUE",
        "category_id": 2,
        "chart_id": 2373,
        "created_at": "2013-01-15 16:43:52.169213",
        "dept_id": 86,
        "feb": 45,
        "id": 3,
        "jan": 60,
        "note": "Two",
        "total_cost": 105,
        "updated_at": "2013-01-15 16:43:52.169213",
        "year_id": 1
    }
]

I then attempt to iterate over the objects and sum the values:

var jan;

for (var i=0;i<data.length;i++){ 
    if(data[i].jan != null){    
        jan += parseFloat(data[i].jan);
        console.log(jan);
    }
}

Printed out in the console is NaN. I've attempted to parse the number as well as leave it raw, but to no avail. Is there something wrong with my objects? Here is a jsFiddle to illustrate: http://jsfiddle.net/5E2pm/3/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var jan = 0; //this should solve it

for (var i=0;i<data.length;i++){ 
    if(data[i].jan != null){    
        jan += parseFloat(data[i].jan);
        console.log(jan);
    }
}

Try this should solve it :)

Explanation as quoted by DON in comments below:

var jan; this will declare variable as undefined, so when you try to add values with undefined you will get as NaN, so the answer here with var jan = 0 will work – DON


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...