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

考虑:

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

这是最好的方法吗?


当前回答

显示如何使用此答案

const object= {key1: 'data', key2: 'data2'};

Object.keys(object).includes('key1') //returns true

我们也可以使用indexOf,我更喜欢includes

其他回答

也可以使用ES6 Reflect对象:

x = {'key': 1};
Reflect.has( x, 'key'); // returns true

Reflect.has的MDN文档可在此处找到。

静态Reflect.has()方法的工作方式类似于函数中的in运算符。

2022年更新

Object.hasOwn()

建议使用Object.hasOwn()而不是Object.hasOwnerProperty(),因为它适用于使用Object.create(null)创建的对象以及已重写继承的hasOwnProperty()方法的对象。虽然可以通过对外部对象调用Object.pr原型.hasOwnProperty()来解决这些问题,但Object.hasOwn()更直观。

实例

const object1 = {
  prop: 'exists'
};

console.log(Object.hasOwn(object1, 'prop'));
// expected output: true

原答覆

我真的被给出的答案弄糊涂了——大多数答案都是完全错误的。当然,您可以拥有具有未定义、null或false值的对象财产。因此,简单地将属性检查减少为this〔property〕的类型,或者更糟糕的是,x.key将给您带来完全误导的结果。

这取决于你要找什么。如果你想知道一个对象是否在物理上包含一个属性(并且它不是来自原型链上的某个地方),那么object.hasOwnProperty就是最好的方法。所有现代浏览器都支持它。(Safari 2.0.1和更早版本中缺少它,但这些版本的浏览器很少再使用了。)

如果您要查找的是一个对象上是否有可迭代的属性(当您迭代对象的财产时,它就会出现),那么在对象中执行:prop将获得您想要的效果。

由于使用hasOwnProperty可能是您想要的,并且考虑到您可能需要回退方法,我向您介绍了以下解决方案:

var obj = {
    a: undefined,
    b: null,
    c: false
};

// a, b, c all found
for ( var prop in obj ) {
    document.writeln( "Object1: " + prop );
}

function Class(){
    this.a = undefined;
    this.b = null;
    this.c = false;
}

Class.prototype = {
    a: undefined,
    b: true,
    c: true,
    d: true,
    e: true
};

var obj2 = new Class();

// a, b, c, d, e found
for ( var prop in obj2 ) {
    document.writeln( "Object2: " + prop );
}

function hasOwnProperty(obj, prop) {
    var proto = obj.__proto__ || obj.constructor.prototype;
    return (prop in obj) &&
        (!(prop in proto) || proto[prop] !== obj[prop]);
}

if ( Object.prototype.hasOwnProperty ) {
    var hasOwnProperty = function(obj, prop) {
        return obj.hasOwnProperty(prop);
    }
}

// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
    if ( hasOwnProperty(obj2, prop) ) {
        document.writeln( "Object2 w/ hasOwn: " + prop );
    }
}

以上是hasOwnProperty()的一个有效的跨浏览器解决方案,但有一个警告:它无法区分原型和实例上相同属性的情况-它只是假设它来自原型。根据你的情况,你可以把它改得更宽或更严,但至少这应该更有帮助。

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

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


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

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

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

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

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

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

x?。如果x.key存在,key返回1,否则未定义