Javascript—安全检查/访问潜在未定义对象的属性的速记符号
在访问jsonObject的errorMessage属性之前,检查jsonObject是否未定义的最短语法是什么Javascript—安全检查/访问潜在未定义对象的属性的速记符号,javascript,Javascript,在访问jsonObject的errorMessage属性之前,检查jsonObject是否未定义的最短语法是什么 var jsonObject = SomeMethodReturningAnObject(); if (jsonObject.errorMessage === undefined) // jsonObject can be undefined and this will throw an error /* success! */ else alert(jsonObjec
var jsonObject = SomeMethodReturningAnObject();
if (jsonObject.errorMessage === undefined) // jsonObject can be undefined and this will throw an error
/* success! */
else
alert(jsonObject.errorMessage);
您可以使用
&&
操作符,因为如果左侧是未定义的
,它不会计算右侧:
if (jsonObject && jsonObject.errorMessage === undefined)
另一种方法是使用
typeof
操作符
在JS中,如果已声明变量但未设置值,例如:
var x;
然后将x
设置为undefined
,以便您可以通过以下方式轻松检查:
if(x) //x is defined
if(!x) //x is undefined
但是,如果您尝试对一个甚至还没有声明的变量执行if(x)
,您将得到您在文章“ReferenceError:x未定义”中提到的错误
在这种情况下,我们需要使用typeof
-进行检查
因此,在您的情况下:
if(typeof jsonObject !== "undefined") {
//jsonObject is set
if(jsonObject.errorMessage) {
//jsonObject set, errorMessage also set
} else {
//jsonObject set, no errorMessage!
}
} else {
//jsonObject didn't get set
}
这是因为如果将一个变量设置为空对象,x={}
,并尝试获取该对象中不存在的变量,例如x.y
,则返回未定义的
,则不会得到引用错误
请注意,typeof
运算符返回一个表示变量类型的字符串,而不是类型本身。因此它将返回“undefined”
而不是undefined
另外,这个非常类似的问题可以帮助您:
希望这有帮助
杰克。我会回答速记法方面的问题,因为你的具体情况更好地由我来解决。从ECMAScript 2018开始,我们就有了,这使得整个过程更加简洁:
if({…jsonObject}.errorMessage){
//我们有错误的消息
}否则{
//jsonObject或jsonObject.errorMessage未定义/错误
//无论哪种情况,我们都没有例外
}
直接的if/else并不完全适合您的情况,因为您实际上有3个状态,其中2个状态被塞进上面的相同if分支中
jsonObject
:失败jsonObject
,Has noerrorMessage
:成功jsonObject
,HaserrorMessage
:失败foo
,实质上是这样做的:
undefined.foo//显然是异常
扩展语法将属性复制到新对象,因此不管发生什么情况,最终都会得到一个对象:
typeof{…undefined}==='object'
因此,通过扩展obj
可以避免直接对潜在的未定义的变量进行操作
还有一些例子:
({…undefined}).foo/==未定义,未引发异常
({…{'foo':'bar'}).foo/=='bar'
如果(!jsonObject.errorMessage)
?@AndroidVid读取未定义或空对象上的errorMessage属性将抛出错误,可能也可以跳过==未定义的
。@Douglas:我想这会产生相反的效果。OP正在检查是否没有错误(这意味着成功)。操作员做什么?@contactmatt:评估左侧,如果错误,评估右侧(否则评估左侧)undefined
是错误的,因此它不会触发在这种情况下会产生错误的表达式。我似乎仍然收到错误“无法读取undefined的属性'errorMessage'
if(x) //x is defined
if(!x) //x is undefined
if(typeof jsonObject !== "undefined") {
//jsonObject is set
if(jsonObject.errorMessage) {
//jsonObject set, errorMessage also set
} else {
//jsonObject set, no errorMessage!
}
} else {
//jsonObject didn't get set
}