javascript - JSON - Uncaught TypeError: Cannot read property of undefined - Stack Overflow

I want take some JSON values and make variable from them, but when I do it I get an error.In first sta

I want take some JSON values and make variable from them, but when I do it I get an error. In first stage JSON array is empty, thats why I used if != null, but even with filled array I get an error.

var tempJS=[];  
$("#sth td").each(function(){
    $this = $(this);
    tempJS.push({"COLOR":$this.attr("data-color"),});
});
console.log(JSON.stringify(tempJS));

if(tempJS!=null) var kolor=tempJS[c-1].COLOR;

Why is the last line giving me the following error:

Uncaught TypeError: Cannot read property 'COLOR' of undefined

I want take some JSON values and make variable from them, but when I do it I get an error. In first stage JSON array is empty, thats why I used if != null, but even with filled array I get an error.

var tempJS=[];  
$("#sth td").each(function(){
    $this = $(this);
    tempJS.push({"COLOR":$this.attr("data-color"),});
});
console.log(JSON.stringify(tempJS));

if(tempJS!=null) var kolor=tempJS[c-1].COLOR;

Why is the last line giving me the following error:

Uncaught TypeError: Cannot read property 'COLOR' of undefined

Share Improve this question edited Aug 2, 2014 at 7:01 Hugo Dozois 8,42812 gold badges55 silver badges59 bronze badges asked Aug 2, 2014 at 1:11 snuuvesnuuve 3151 gold badge4 silver badges14 bronze badges 1
  • The error is very explicit, what is undefined is tempJS[c-1], where is that "c" on the code?, beside you are checking that tempJS is not null, it assigning tempJS[c-1], you should check for the same thing – Lu Roman Commented Aug 2, 2014 at 1:20
Add a ment  | 

2 Answers 2

Reset to default 3

If you try on the console:

[]==null
> false

you'll see that returns false. This means that if you check if the array equals null you will always get a false, and always run the code in the if statement.

You should do this instead:

if(tempJS.length) var kolor=tempJS[c-1].COLOR;

You don't need if(tempJS.length > 0) because every number is treated like true except 0 that means false.

A zero-length array is not same as null. Try testing if (tempJS.length > 0) ...

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745444171a4627967.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信