Javascript检查对象属性是否存在,即使对象未定义 [英] Javascript check if object property exists, even when object is undefined
问题描述
我想检查一个对象是否存在,并且有一个属性。目前我收到一个myObject is undefined错误,它会停止检查。
I want to check if an object exists, and has a property. Currently I get a "myObject is undefined" error that stops the check.
即使myObject可能不存在,如何使以下内容仍能正常工作?
How can I make the following still work correctly even when myObject may not exist?
if (myObject.myProperty) {
...
} else {
...
}
我试图甚至检查对象/变量是否存在但是收到错误:
I am trying to just even check if a object / variable exists but getting an error:
if(foo){console.log('hello'); }
给出错误Uncaught ReferenceError:foo未定义。这是一个jsfiddle http://jsfiddle.net/cfUss/
if (foo) { console.log('hello'); }
gives the error Uncaught ReferenceError: foo is not defined. Here is a jsfiddle http://jsfiddle.net/cfUss/
推荐答案
您可以使用短路&&
运营商:
You can use the "short circuit" &&
operator:
if (myObject && myObject.myProperty) {
...
}
如果 myObject
为falsey(例如未定义)& ;&
运算符不会试图评估右手表达式,从而避免尝试引用不存在的对象的属性。
If myObject
is "falsey" (e.g. undefined) the &&
operator won't bother trying to evaluate the right-hand expression, thereby avoiding the attempt to reference a property of a non-existent object.
变量 myObject
必须已经声明了,上面的测试是针对是否已经分配了一个价值。
The variable myObject
must have course already have been declared, the test above is for whether it has been assigned a defined value.
这篇关于Javascript检查对象属性是否存在,即使对象未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!