[英]JSON - Uncaught TypeError: Cannot read property of undefined
I want take some JSON values and make variable from them, but when I do it I get an error. 我想要一些JSON值并从中获取变量,但是当我这样做时会出现错误。 In first stage JSON array is empty, thats why I used
if != null
, but even with filled array I get an error. 在第一阶段,JSON数组为空,这就是为什么我使用
if != null
,但即使使用填充数组也遇到错误。
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
未捕获的TypeError:无法读取未定义的属性“ COLOR”
If you try on the console: 如果您在控制台上尝试:
[]==null
> false
you'll see that returns false
. 您会看到返回
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. 这意味着,如果检查数组是否等于
null
,则始终会得到false,并始终在if
语句中运行代码。
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
. 您不需要
if(tempJS.length > 0)
因为每个数字都被当作true
对待,除了0
意味着false
。
A zero-length array is not same as null. 零长度数组与null不同。 Try testing
if (tempJS.length > 0) ...
尝试测试
if (tempJS.length > 0) ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.