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

考虑:

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

这是最好的方法吗?


当前回答

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

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

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

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

其他回答

if(x.hasOwnProperty("key")){
  // …
}

因为

if(x.key){
  // …
}

如果x.key错误(例如,x.key==“”),则失败。

好吧,看来我的答案是正确的,除非你不想继承财产:

if (x.hasOwnProperty('key'))

以下是包含继承财产的其他选项:

if (x.key) // Quick and dirty, but it does the same thing as below.

if (x.key !== undefined)

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

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

or

myObject.hasOwnProperty('myKey')

or

typeof myObject.myKey !== 'undefined'

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

考虑Javascript中的以下对象

const x = {key: 1};

可以使用in运算符检查对象上是否存在该属性:

console.log("key" in x);

您还可以使用for-in循环遍历对象的所有财产,然后检查特定属性:

for (const prop in x) {
    if (prop === "key") {
        //Do something
    }
}

您必须考虑此对象属性是否可枚举,因为非可枚举财产不会显示在for-in循环中。此外,如果可枚举属性隐藏了原型的不可枚举属性,它将不会在InternetExplorer8和更早版本中显示。

如果您想要所有实例财产的列表,无论是否可枚举,您可以使用

Object.getOwnPropertyNames(x);

这将返回对象上存在的所有财产的名称数组。

反射提供了可用于与Javascript对象交互的方法。静态Reflect.has()方法的工作方式类似于函数中的in运算符。

console.log(Reflect.has(x, 'key'));
// expected output: true

console.log(Reflect.has(x, 'key2'));
// expected output: false

console.log(Reflect.has(object1, 'toString'));
// expected output: true

最后,您可以使用typeof运算符直接检查对象属性的数据类型:

if (typeof x.key === "undefined") {
    console.log("undefined");
}

如果对象上不存在该属性,它将返回字符串undefined。否则,它将返回适当的属性类型。但是,请注意,这并不总是检查对象是否具有属性的有效方法,因为您可以将属性设置为undefined,在这种情况下,使用typeof x.key仍将返回true(即使该键仍在对象中)。

类似地,您可以通过直接与未定义的Javascript属性进行比较来检查属性是否存在

if (x.key === undefined) {
    console.log("undefined");
}

除非在x对象上特别将key设置为undefined,否则这应该有效

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)

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