如何检查JavaScript中的对象属性是否未定义?


当前回答

我们ES6可以与!!将所有值转换为布尔值。使用此选项,所有假值都将变为假。

第一种解决方案

if (!(!!variable)) {
    // Code
}

第二种解决方案

if (!variable) {
    // Code
}

其他回答

交叉发布我对相关问题的回答如何在JavaScript中检查“undefined”?。

具体到这个问题,请参阅someObject的测试用例<无论什么>。


说明各种答案结果的一些场景:http://jsfiddle.net/drzaus/UVjM4/

(请注意,在测试中使用var会在作用域包装器中产生差异)

参考代码:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

结果:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

我想向您展示我正在使用的一些东西,以保护未定义的变量:

Object.defineProperty(window, 'undefined', {});

这禁止任何人更改window.undefined值,从而破坏基于该变量的代码。如果使用“usestrict”,任何试图更改其值的行为都将以错误告终,否则将被忽略。

回顾

许多给定的答案给出了错误的结果,因为它们没有区分对象属性不存在的情况和属性值未定义的情况。以下是最流行的解决方案的证明:

让obj={a: 666中,u: undefined//“u”属性的值为“undefined”//“x”属性不存在}console.log('>>>好结果:');console.log('A',obj中的“u”,obj的“x”);console.log('B',obj.hasOwnProperty(“u”),obj.hasOwnProperty(“x”));console.log('\n>>>坏结果:');console.log('C',obj.u==未定义,obj.x==未确定);console.log('D',obj.u==未定义,obj.x==未定义);console.log('E',obj[“u”]==未定义,obj'“x”]===未定义);console.log('F',obj[“u”]==未定义,obj'“x”]===未定义);console.log('G',!obj.u,!obj.x);console.log('H',对象类型u=='未定义',对象的类型x=='不定义');

检查是否存在密钥的一种简单方法是:

if (key in obj) {
  // Do something
} else {
  // Create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true

“if(window.x){}”是错误安全的

很可能您想要if(window.x)。即使x尚未声明(var x;),该检查也是安全的-浏览器不会抛出错误。

示例:我想知道我的浏览器是否支持历史API

if (window.history) {
    history.call_some_function();
}

工作原理:

window是一个包含所有全局变量作为其成员的对象,尝试访问不存在的成员是合法的。如果x尚未声明或未设置,则window.x返回undefined。undefined在if()求值时导致false。