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


当前回答

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

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

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

其他回答

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

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

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

const hasZero = 0 in obj

console.log(hasZero) // true

交叉发布我对相关问题的回答如何在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

回顾

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

让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(o.myProperty === undefined) {
  alert("myProperty value is the special value `undefined`");
}

要检查对象是否实际上没有这样的属性,并且当您尝试访问它时,默认情况下会返回undefined:

if(!o.hasOwnProperty('myProperty')) {
  alert("myProperty does not exist");
}

要检查与标识符关联的值是否为未定义的特殊值,或者该标识符是否尚未声明:

if(typeof myVariable === 'undefined') {
  alert('myVariable is either the special value `undefined`, or it has not been declared');
}

注意:最后一个方法是引用未声明的标识符而不出现早期错误的唯一方法,这与值为undefined不同。

在ECMAScript 5之前的JavaScript版本中,全局对象上名为“undefined”的属性是可写的,因此,如果不小心重新定义了foo==undefineed,则简单的检查可能会出现意外的行为。在现代JavaScript中,属性是只读的。

然而,在现代JavaScript中,“undefined”不是关键字,因此函数内部的变量可以命名为“undefine”,并隐藏全局属性。

如果您担心这种(不太可能的)边缘情况,可以使用void运算符获取特殊的未定义值本身:

if(myVariable === void 0) {
  alert("myVariable is the special value `undefined`");
}

您可以像这样使用JavaScript对象函数:

var ojb ={
    age: 12
}

if(ojb.hasOwnProperty('name')){
    console.log('property exists and is not undefined');
}

如果获得该属性或该属性未定义,则上述方法返回true。