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:
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 1Uncaught TypeError: Cannot read property 'COLOR' of undefined
- 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
2 Answers
Reset to default 3If 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条)