简体   繁体   English

JSON-未捕获的TypeError:无法读取未定义的属性

[英]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.

相关问题 未捕获的类型错误:无法读取未定义 JSON 的属性 - Uncaught TypeError: Cannot read property of undefined JSON json出现Uncaught TypeError错误:无法读取未定义的属性“选择” - Error with json Uncaught TypeError: Cannot read property 'choices' of undefined 未捕获的TypeError:无法读取json_encode()上未定义的属性“ length” - Uncaught TypeError: Cannot read property 'length' of undefined on json_encode() Jquery json:未捕获TypeError:无法读取未定义的属性'xx' - Jquery json : Uncaught TypeError: Cannot read property 'xx' of undefined JSON JQUERY未捕获的TypeError:无法读取未定义的属性“ length” - JSON JQUERY Uncaught TypeError: Cannot read property 'length' of undefined Uncaught TypeError:无法读取jQuery $ .each和JSON中未定义的属性“ length” - Uncaught TypeError: Cannot read property 'length' of undefined in jQuery $.each and JSON 未捕获的TypeError无法读取json数据未定义的属性'image' - Uncaught typeerror cannot read property 'image' of undefined with json data 未捕获的类型错误:无法使用 JSON 读取未定义的属性“0” - Uncaught TypeError: Cannot read property '0' of undefined using JSON d3.json:“未捕获的TypeError:无法读取未定义的属性'children'” - d3.json: “Uncaught TypeError: Cannot read property 'children' of undefined” 未捕获的类型错误:无法读取简单 JSON 数组的未定义属性“长度” - Uncaught TypeError: Cannot read property 'length' of undefined for simple JSON array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM