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

考虑:

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

这是最好的方法吗?


当前回答

现在使用ECMAScript22,我们可以使用hasOwn而不是hasOwnProperty(因为这个特性有缺陷)

Object.hasOwn(obj, propKey)

其他回答

给定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)

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

让我们在这里消除一些困惑。首先,让我们通过假设hasOwnProperty已经存在来简化;目前使用的绝大多数浏览器都是如此。

如果传递给它的属性名已添加到对象中,hasOwnProperty返回true。它完全独立于分配给它的实际值,而实际值可能完全未定义。

因此:

var o = {}
o.x = undefined

var a = o.hasOwnProperty('x')  // a is true
var b = o.x === undefined // b is also true

然而:

var o = {}

var a = o.hasOwnProperty('x')  // a is now false
var b = o.x === undefined // b is still true

问题是当原型链中的对象具有值为undefined的属性时会发生什么?hasOwnProperty将为false,也将为false!==未定义。然而,对于。。中仍将在枚举中列出它。

最重要的是,没有跨浏览器的方法(因为Internet Explorer不公开__prototype__)来确定特定标识符是否未附加到对象或其原型链中的任何内容。

使用Undercore.js或(甚至更好)Lodash:

_.has(x, 'key');

它调用Object.prototype.hasOwnProperty,但(a)比type短,(b)使用“hasOwnProperty的安全引用”(即,即使hasOwnProperty被覆盖,它也能工作)。

特别是,Lodash将_定义为:

function has(object, key) {
  return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty

是的,它是:)我想你也可以做Object.protype.hasOwnProperty.call(x,'key'),如果x有一个名为hasOwnProperty:)的属性,这也应该有效

但这是对自身财产的测试。如果你想检查它是否有一个属性也可能是固有的,你可以使用typeof x.foo!='未定义”。