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

考虑:

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

这是最好的方法吗?


当前回答

对象上存在一个方法“hasOwnProperty”,但不建议直接调用此方法,因为有时可能是对象为空或对象上存在某些属性,例如:{hasOwnProperty:false}

因此,更好的方法是:

//好的var obj={“bar”:“here bar desc”}console.log(Object.pr原型.hasOwnProperty.call(obj,“bar”));//最佳const has=Object.prototype.hasOwnProperty;//在模块范围内缓存查找一次。console.log(has.call(obj,“bar”));

其他回答

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

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])。。。因为我觉得它更可读。

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

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

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

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

不要执行此对象。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));

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

if (x.hasOwnProperty('key'))

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

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

if (x.key !== undefined)