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

考虑:

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

这是最好的方法吗?


当前回答

带反射的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

其他回答

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)

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

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

要检查属性是否存在,无论值如何,请使用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被正确使用的情况,特别是考虑到它的继承问题

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

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

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

Object.hasOwn(obj, propKey)

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

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

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