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

考虑:

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

这是最好的方法吗?


当前回答

hasOwnProperty“可用于确定对象是否具有指定的属性作为该对象的直接属性;与in运算符不同,此方法不检查对象的原型链。”

因此,最有可能的是,根据您的问题,您不想使用hasOwnProperty,它确定属性是否直接附加到对象本身,。

如果要确定该属性是否存在于原型链中,可以使用如下方式:

if (prop in object) { // Do something }

其他回答

以下是针对特定情况的另一个选项。:)

如果要测试对象上的成员,并想知道它是否已设置为以下以外的值:

''假的无效的未定义0...

那么您可以使用:

var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
    // member is set, do something
}

对象上存在一个方法“hasOwnProperty”,但不建议直接调用此方法,因为有时可能是对象为空或对象上存在某些属性,例如:{hasOwnProperty:false}

因此,更好的方法是:

//好的var obj={“bar”:“here bar desc”}console.log(Object.pr原型.hasOwnProperty.call(obj,“bar”));//最佳const has=Object.prototype.hasOwnProperty;//在模块范围内缓存查找一次。console.log(has.call(obj,“bar”));

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)

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

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

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

您需要使用方法object.hasOwnProperty(属性)。如果对象具有该属性,则返回true,如果对象没有,则返回false。