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

考虑:

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

这是最好的方法吗?


当前回答

如果您正在搜索属性,请选择“否”。您需要:

if ('prop' in obj) { }

通常,您不应该关心属性是否来自原型或对象。

然而,因为您在示例代码中使用了“key”,所以看起来您将对象视为哈希,在这种情况下,您的答案是有意义的。所有散列键都是对象中的财产,您可以避免原型提供额外的财产。

约翰·雷格的回答很全面,但我认为不清楚。特别是当在obj中使用“rop”时。

其他回答

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

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

if(x.hasOwnProperty("key")){
  // …
}

因为

if(x.key){
  // …
}

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

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

带反射的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.key !== undefined)

Armin Ronacher似乎已经击败了我,但是:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

康拉德·鲁道夫(Konrad Rudolph)和阿明·罗纳彻(Armin Ronacher)指出,一个更安全但更慢的解决方案是:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};