var data = [{
"error": false,
"date": "09-02-2016",
"day": "5",
"checkin": "20:29:11",
"checkout": null,
"break_timein": null,
"break_timeout": null,
"checkin_remarks": "test",
"checkout_remarks": null,
"break_time_remarks": null
}];
console.log(data[0].checkin)
console.log(data[0].break_timein)
console.log(data[0].break_timein.length > 0 || data[0].break_timein != null)
对于break_timein
,当我console.log它时,它返回null,但是当我获得长度时,它返回Cannot read property 'length' of null
这是为什么?
最佳答案
I understand that it only appears when there is not property
break_timein
but it is there its justnull
您在这里得出了错误的结论。该错误与属性是否存在无关。
当属性不存在并且您尝试访问其上的属性时,您会收到以下错误:
var foo = {};
foo.bar.baz;
// Uncaught TypeError: Cannot read property 'baz' of undefined
这句话中的“未定义”并不是指属性的存在,而是指值未定义
。在 JavaScript 中,当访问不存在的属性时,访问该属性将返回值 undefined
:
foo.bar
// undefined
还有其他情况会创建 undefined
,例如当您定义没有初始值的变量时:
var abc;
abc;
// undefined
知道我们可以测试当我们直接访问 undefined
上的属性时会发生什么:
undefined.foo
// Uncaught TypeError: Cannot read property 'foo' of undefined
这会引发与上面相同的错误,因此它与属性访问没有任何关系。
<小时/>现在我们已经确定 undefined
不能在属性访问上下文中使用。
null
是另一个类似的值:
null.foo
// Uncaught TypeError: Cannot read property 'foo' of null
是什么让 null
和 undefined
与其他原始值(字符串、数字、 bool 值)不同,它们表现出这种行为?
null
和 undefined
实际上是两种唯一数据类型的值:Null 和 Undefined。
这些数据类型没有有对象包装器。字符串、数字和 bool 值可以以两种形式存在:作为原始值和作为对象值:
var primitive = "foo";
var object = new String("foo");
当您访问原始值的属性时,例如"foo".length
,JavaScript automatically converts the primitive value到 temporary object value ,类似于new String("foo").length
。
但是由于没有 Null 和 Undefined
等价的对象(从没有 Null
或 Undefined
函数这一事实可以看出),这是无法完成的,因此会抛出错误。
关于javascript - 访问json中的数据未获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293076/