Javascript - 安全检查/访问潜在未定义对象上的属性的简写表示法

时间:2012-03-06 18:17:49

标签: javascript

在访问errorMessage属性之前,检查 jsonObject 是否未定义的最短语法是什么?

var jsonObject = SomeMethodReturningAnObject();

if (jsonObject.errorMessage === undefined) // jsonObject can be undefined and this will throw an error
   /* success! */
else
   alert(jsonObject.errorMessage);

5 个答案:

答案 0 :(得分:5)

您可以使用&&运算符,因为如果左侧是undefined,它不会评估右侧:

if (jsonObject && jsonObject.errorMessage === undefined)

答案 1 :(得分:3)

另一种方法是使用typeof运算符。

在JS中,如果已声明变量但未设置值,例如: var x;

然后x设置为undefined,以便您可以通过以下方式轻松检查:

if(x) //x is defined
if(!x) //x is undefined

但是,如果您尝试对尚未声明的变量执行if(x),您将收到您在帖子中提到的错误,“ReferenceError:x未定义”< / em>的

在这种情况下,我们需要使用typeof - MSDN Docs - 来检查。

所以在你的情况下如下:

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,则得到undefined 1}}返回,你没有得到ReferenceError。

请注意typeof运算符返回表示变量类型的字符串,而不是类型本身。因此它会返回"undefined"而不是undefined

此外,关于SO的这个非常相似的问题可以帮助您:How to check a not-defined variable in JavaScript

希望这有帮助。

杰克。

答案 2 :(得分:1)

var jsonObject = SomeMethodReturningAnObject();

if (jsonObject && jsonObject.errorMessage === undefined)
   /* success! */
else
   alert(!jsonObject ? "jsonObject not defined" : jsonObject.errorMessage);

答案 3 :(得分:0)

if(jsonObject)
{
    if (!jsonObject.errorMessage)
        // success..
        foo()    
    else
        alert(jsonObject.errorMessage);
}

答案 4 :(得分:0)

我将回答速记符号方面,因为an existing answer可以更好地满足您的特定情况。从ECMAScript 2018开始,我们有了spread syntax,这使整个事情变得更加简洁:


if ( {...jsonObject}.errorMessage ) {
    // we have errorMessage
} else {
    // either jsonObject or jsonObject.errorMessage are undefined / falsey
    // in either case, we don't get an exception
}

直的if / else不适合您的情况,因为您实际上有3个状态,如果上面的分支中有2个被塞入相同的状态。

  1. jsonObject:失败
  2. jsonObject,没有errorMessage:成功
  3. jsonObject,有errorMessage:失败

这为什么起作用:

假设对象是未定义的,则从对象foo访问属性obj基本上是这样:

undefined.foo //exception, obviously

Spread语法会将属性复制到新对象,因此无论如何,您最终都会得到对象

typeof {...undefined} === 'object'

因此,通过传播obj可以避免直接对潜在的undefined变量进行操作。

更多示例:

({...undefined}).foo  // === undefined, no exception thrown

({...{'foo': 'bar'}}).foo // === 'bar'