简体   繁体   中英

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/

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

I like this approach. It basically sets the value to 0 on the first iteration when jan doesn't exist.

jan = (jan || 0) + parseFloat(data[i].jan);

you need to initialize jan first

var jan = 0; 

here's the example - link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM