Object returning NaN when sum values

前端 未结 3 1700
名媛妹妹
名媛妹妹 2020-12-02 02:23

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 t

相关标签:
3条回答
  • 2020-12-02 02:28

    you need to initialize jan first

    var jan = 0; 
    

    here's the example - link

    0 讨论(0)
  • 2020-12-02 02:31

    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);
    
    0 讨论(0)
  • 2020-12-02 02:50
    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

    0 讨论(0)
提交回复
热议问题