求和值时对象返回NaN [英] Object returning NaN when sum values
问题描述
我承认我在JavaScript和JSON方面很弱.我花了很多时间试图弄清楚为什么将我的对象中的数字加在一起后会返回NaN.考虑到这一点,下面是我的JSON,将其存储到变量中:
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);
}
}
在控制台中打印出的是NaN
.我试图解析该数字并将其保留为原始数据,但无济于事.我的物体有问题吗?这是一个jsFiddle来说明: http://jsfiddle.net/5E2pm/3/
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 :)
DON在以下评论中引用的解释:
Explanation as quoted by DON in comments below:
var jan;这会将变量声明为undefined,因此当您尝试 添加未定义的值,您将获得NaN,所以这里的答案是 var jan = 0将起作用– DON
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
这篇关于求和值时对象返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!