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

考虑:

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

这是最好的方法吗?


当前回答

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

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

其他回答

迭代对象自身财产的更好方法:

如果要在不使用hasOwnProperty()检查的情况下迭代对象的财产,用于(let key of Object.keys(stud)){}方法:

for(let key of Object.keys(stud)){
  console.log(key); // will only log object's Own properties
}

完整示例并与hasOwnProperty()中的for进行比较

function Student() {
  this.name = "nitin";
}

Student.prototype = {
  grade: 'A'
}

let stud = new Student();

// for-in approach
for(let key in stud){
  if(stud.hasOwnProperty(key)){
    console.log(key); // only outputs "name"
  }
} 

//Object.keys() approach
for(let key of Object.keys(stud)){
  console.log(key);
}

注意:由于严格的模式和OwnProperty,以下内容现在基本上已过时。正确的解决方案是使用strict模式,并使用obj.hasOwnProperty检查是否存在属性。这个答案早于这两种方法,至少在广泛实施时(是的,它已经过时了)。将以下内容作为历史笔记。


请记住,如果不使用严格模式,undefined(不幸的是)不是JavaScript中的保留词。因此,某人(显然是其他人)可能会有重新定义它的宏伟想法,破坏您的代码。

因此,更稳健的方法如下:

if (typeof(x.attribute) !== 'undefined')

另一方面,这种方法更冗长,也更慢-/

一种常见的替代方法是确保undefined实际上是undefineed,例如,将代码放入一个函数中,该函数接受一个未传递值的附加参数,称为undefinede。为了确保它没有传递值,您可以立即调用它,例如:

(function (undefined) {
    … your code …
    if (x.attribute !== undefined)
        … mode code …
})();

带反射的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
if(x.hasOwnProperty("key")){
  // …
}

因为

if(x.key){
  // …
}

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

对于测试简单对象,请使用:

if (obj[x] !== undefined)

如果您不知道它是什么对象类型,请使用:

if (obj.hasOwnProperty(x))

所有其他选项都较慢。。。

细节

对Node.js下100000000个周期的性能评估,其他人在这里建议了五个选项:

function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }

评估告诉我们,除非我们特别想检查对象的原型链以及对象本身,否则不应使用通用形式:

if (X in Obj)...

根据使用情况,速度慢2到6倍

hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s

总之,如果您的Obj不一定是一个简单的对象,并且您希望避免检查对象的原型链,并确保x由Obj直接拥有,请使用if(Obj.hasOwnProperty(x))。。。。

否则,当使用简单对象而不担心对象的原型链时,使用if(typeof(obj[x])!=='undefined')。。。是最安全、最快的方式。

如果你使用一个简单的对象作为哈希表,并且从不做任何奇怪的事情,我会使用If(obj[x])。。。因为我觉得它更可读。