Json 属性 的未定义对象未打印。为什么?
Json property of an undefined object not printing. Why?
我遇到了一个我不太理解的简单行为。我正在尝试检查 JSON 对象数组的有效性,这里的核心点是用户 'choses' 它的大小(例如,如果他键入 2, 将有 2 个对象).
每个对象都应该有一个名称和一个版本。
我想确保他输入了一些东西,所以当他点击提交按钮时,我正在检查这种声明:
if (myarray[0].name !== undefined || myarray.name !== null)
{
// Do some crazy stuff as crazy a return;
}
而且我没有工作。当我去进一步检查时(console.log,哇),我注意到了这一点:
console.log(myarray); // Prints '[]' because it is empty
console.log(myarray[0]); // Prints 'undefined', seems legit
console.log(myarray[0].name); // Prints ... Well, nothing
为什么第三个console.log
不打印undefined
?未定义对象的任何 属性 应该是 undefined
,或者我在 JavaScript 中缺少什么?
提前致谢!
Why does the third console.log
does not print undefined
?
因为抛出异常:TypeError: Cannot read property 'name' of undefined
。当您尝试从 undefined
或 null
.
读取 属性 时会发生这种情况
我遇到了一个我不太理解的简单行为。我正在尝试检查 JSON 对象数组的有效性,这里的核心点是用户 'choses' 它的大小(例如,如果他键入 2, 将有 2 个对象).
每个对象都应该有一个名称和一个版本。
我想确保他输入了一些东西,所以当他点击提交按钮时,我正在检查这种声明:
if (myarray[0].name !== undefined || myarray.name !== null)
{
// Do some crazy stuff as crazy a return;
}
而且我没有工作。当我去进一步检查时(console.log,哇),我注意到了这一点:
console.log(myarray); // Prints '[]' because it is empty
console.log(myarray[0]); // Prints 'undefined', seems legit
console.log(myarray[0].name); // Prints ... Well, nothing
为什么第三个console.log
不打印undefined
?未定义对象的任何 属性 应该是 undefined
,或者我在 JavaScript 中缺少什么?
提前致谢!
Why does the third
console.log
does not printundefined
?
因为抛出异常:TypeError: Cannot read property 'name' of undefined
。当您尝试从 undefined
或 null
.