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

考虑:

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

这是最好的方法吗?


当前回答

使用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

其他回答

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)

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

考虑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,否则这应该有效

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

if (x.hasOwnProperty('key'))

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

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

if (x.key !== undefined)

带反射的ECMAScript 6解决方案。创建如下包装:

/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
@param obj    The object or array to be searched.
@param key    The name of the property or key.
@param defVal Optional default version of the command-line parameter [default ""]
@return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
   "use strict";
   var retVal = (typeof defVal === 'undefined' ? "" : defVal);
   if ( Reflect.has( obj, key) ) {
       return Reflect.get( obj, key);
   }
   return retVal;
}  // getSafeReflectArg

一些更简单和简短的选项取决于具体的使用情况:

要检查属性是否存在,无论值如何,请使用in运算符(b中的“a”)要检查变量的属性值,请使用括号符号(obj[v])要将属性值检查为true,请使用optional链接(?)要检查属性值布尔值,请使用double not/bang bang/(!!)要设置空/未定义检查的默认值,请使用空合并运算符(??)要设置假值检查的默认值,请使用短路逻辑OR运算符(||)

运行代码段以查看结果:

让obj1={prop:undefined};console.log(1,obj1中的“prop”);console.log(1,obj1?.prop);let obj2=未定义;//console.log(2,obj2中的“prop”);将引发,因为obj2未定义console.log(2,“prop”in(obj2??{}))console.log(2,obj2?.prop);让obj3={prop:false};console.log(3,obj3中的“prop”);console.log(3,!!obj3?.prop);让obj4={prop:null};let look=“prop”console.log(4,obj4中的“prop”);console.log(4,obj4?.[look]);让obj5={prop:true};console.log(5,obj5中的“prop”);console.log(5,obj5?.prop==true);让obj6={otherProp:true};look=“其他道具”console.log(6,obj6中的“prop”);console.log(6,obj6.look)//应该使用括号符号让obj7={prop:“”};console.log(7,obj7中的“prop”);console.log(7,obj7?.prop||“空”);

我很少看到hasOwn被正确使用的情况,特别是考虑到它的继承问题