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


当前回答

问题归结为三种情况:

对象具有属性,其值未定义。对象具有属性,其值未定义。对象没有属性。

这告诉了我们一些我认为重要的事情:

未定义成员和具有未定义值的已定义成员之间存在差异。

但不幸的是,obj.foo的类型并不能告诉我们这三种情况中的哪一种。然而,我们可以将其与obj中的“foo”结合起来,以区分情况。

                               |  typeof obj.x === 'undefined' | !("x" in obj)
1.                     { x:1 } |  false                        | false
2.    { x : (function(){})() } |  true                         | false
3.                          {} |  true                         | true

值得注意的是,这些测试对于空条目也是相同的

                               |  typeof obj.x === 'undefined' | !("x" in obj)
                    { x:null } |  false                        | false

我认为,在某些情况下,检查属性是否存在比检查是否未定义更有意义(而且更清楚),而这种检查唯一不同的情况是情况2,这是对象中实际条目具有未定义值的罕见情况。

例如:我刚刚重构了一堆代码,这些代码对对象是否具有给定属性进行了大量检查。

if( typeof blob.x != 'undefined' ) {  fn(blob.x); }

如果不检查未定义,则更清楚。

if( "x" in blob ) { fn(blob.x); }

但正如前面提到的,这些并不完全相同(但已经足够满足我的需求)。

其他回答

Object.hasOwnProperty(o,'propertyname');

然而,这并不能通过原型链进行查找。

所有答案都不完整。这是了解存在“定义为未定义”属性的正确方法:

var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
  return ((prop in obj) && (typeof obj[prop] == 'undefined'));
};

例子:

var a = { b : 1, e : null };
a.c = a.d;

hasUndefinedProperty(a, 'b'); // false: b is defined as 1
hasUndefinedProperty(a, 'c'); // true: c is defined as undefined
hasUndefinedProperty(a, 'd'); // false: d is undefined
hasUndefinedProperty(a, 'e'); // false: e is defined as null

// And now...
delete a.c ;
hasUndefinedProperty(a, 'c'); // false: c is undefined

遗憾的是,这是正确的答案,却被错误的答案所掩盖>_<

所以,对于任何路过的人,我会免费给你未定义的!!

var undefined ; undefined ; // undefined
({}).a ;                    // undefined
[].a ;                      // undefined
''.a ;                      // undefined
(function(){}()) ;          // undefined
void(0) ;                   // undefined
eval() ;                    // undefined
1..a ;                      // undefined
/a/.a ;                     // undefined
(true).a ;                  // undefined

解决方案不正确。在JavaScript中,

null == undefined

将返回true,因为它们都“强制”为布尔值,并且都为false。正确的方法是检查

if (something === undefined)

这是身份运算符。。。

查看注释,对于那些想同时检查两者的人来说,它是未定义的还是其值为空:

//Just in JavaScript
var s; // Undefined
if (typeof s == "undefined" || s === null){
    alert('either it is undefined or value is null')
}

如果您使用的是jQueryLibrary,那么jQuery.isEmptyObject()将足以满足这两种情况,

var s; // Undefined
jQuery.isEmptyObject(s); // Will return true;

s = null; // Defined as null
jQuery.isEmptyObject(s); // Will return true;

//Usage
if (jQuery.isEmptyObject(s)) {
    alert('Either variable:s is undefined or its value is null');
} else {
     alert('variable:s has value ' + s);
}

s = 'something'; // Defined with some value
jQuery.isEmptyObject(s); // Will return false;

我很惊讶我还没有看到这个建议,但它比使用typeof测试更具特异性。如果您需要知道对象属性是用undefined初始化的还是从未初始化过,请使用Object.getOwnPropertyDescriptor():

// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');

if (typeof descriptor === 'undefined') {
  // was never initialized
} else if (typeof descriptor.value === 'undefined') {
  if (descriptor.get || descriptor.set) {
    // is an accessor property, defined via getter and setter
  } else {
    // is initialized with `undefined`
  }
} else {
  // is initialized with some other value
}