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

考虑:

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

这是最好的方法吗?


当前回答

您可以使用以下方法-

var obj = {a:1}
console.log('a' in obj)               // 1
console.log(obj.hasOwnProperty('a'))  // 2
console.log(Boolean(obj.a))         // 3

以下方法之间的区别如下-

在第一和第三种方法中,我们不仅搜索对象,还搜索其原型链。如果对象没有该属性,但该属性存在于其原型链中,则该对象将为true。

变量obj={a: 2,__原型__:{b:2}}console.log(obj中的'b')console.log(布尔(obj.b))

第二种方法只检查其自身的财产。示例-

变量obj={a: 2,__原型__:{b:2}}console.log(obj.hasOwnProperty('b'))

第一种方法和第三种方法的区别在于,如果有一个属性的值未定义,则第三种方式将为false,而第一种方法将为true。

变量obj={b:未定义}console.log(布尔(obj.b))console.log(obj中的'b');

其他回答

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

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

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

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

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

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(key))。这真的很糟糕,因为这些方法可能会被相关对象上的财产隐藏起来-请考虑{hasOwn Property:false}-或者,对象可能是空对象(object.create(null))。

最好的方法是执行Object.pr原型.hasOwnProperty.call(Object,key)或:

const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(object, key));
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));

您可以使用此选项(但请阅读以下警告):

变量x={“密钥”:1};如果(x中的“键”){console.log('has');}

但要注意:即使x是一个空对象,x中的“constructor”也会返回true。最好使用Object.hasOwn(x,'key')。