如何检查对象在JavaScript中是否具有特定属性?

考虑:

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}

这是最好的方法吗?


当前回答

if (x.key !== undefined)

Armin Ronacher似乎已经击败了我,但是:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

康拉德·鲁道夫(Konrad Rudolph)和阿明·罗纳彻(Armin Ronacher)指出,一个更安全但更慢的解决方案是:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};

其他回答

注意:由于严格的模式和OwnProperty,以下内容现在基本上已过时。正确的解决方案是使用strict模式,并使用obj.hasOwnProperty检查是否存在属性。这个答案早于这两种方法,至少在广泛实施时(是的,它已经过时了)。将以下内容作为历史笔记。


请记住,如果不使用严格模式,undefined(不幸的是)不是JavaScript中的保留词。因此,某人(显然是其他人)可能会有重新定义它的宏伟想法,破坏您的代码。

因此,更稳健的方法如下:

if (typeof(x.attribute) !== 'undefined')

另一方面,这种方法更冗长,也更慢-/

一种常见的替代方法是确保undefined实际上是undefineed,例如,将代码放入一个函数中,该函数接受一个未传递值的附加参数,称为undefinede。为了确保它没有传递值,您可以立即调用它,例如:

(function (undefined) {
    … your code …
    if (x.attribute !== undefined)
        … mode code …
})();

如果您正在搜索属性,请选择“否”。您需要:

if ('prop' in obj) { }

通常,您不应该关心属性是否来自原型或对象。

然而,因为您在示例代码中使用了“key”,所以看起来您将对象视为哈希,在这种情况下,您的答案是有意义的。所有散列键都是对象中的财产,您可以避免原型提供额外的财产。

约翰·雷格的回答很全面,但我认为不清楚。特别是当在obj中使用“rop”时。

给定myObject对象和“myKey”作为密钥名称:

Object.keys(myObject).includes('myKey')

or

myObject.hasOwnProperty('myKey')

or

typeof myObject.myKey !== 'undefined'

最后一个被广泛使用,但(正如其他答案和评论中所指出的)它也可以匹配从Object原型派生的键。

JavaScript现在正在发展壮大,因为它现在有好的甚至有效的方法来检查它。

以下是检查对象是否具有特定属性的一些简单方法:

使用hasOwnProperty()

const hero = {
  name: 'Batman'
};

hero.hasOwnProperty('name');     // => true
hero.hasOwnProperty('realName'); // => false

在中使用关键字/运算符

const hero = {
  name: 'Batman'
};

'name' in hero;     // => true
'realName' in hero; // => false

与未定义的关键字比较

const hero = {
  name: 'Batman'
};

hero.name;     // => 'Batman'
hero.realName; // => undefined

// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)

有关详细信息,请查看此处。

也可以使用ES6 Reflect对象:

x = {'key': 1};
Reflect.has( x, 'key'); // returns true

Reflect.has的MDN文档可在此处找到。

静态Reflect.has()方法的工作方式类似于函数中的in运算符。