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

考虑:

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

这是最好的方法吗?


当前回答

以下是针对特定情况的另一个选项。:)

如果要测试对象上的成员,并想知道它是否已设置为以下以外的值:

''假的无效的未定义0...

那么您可以使用:

var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
    // member is set, do something
}

其他回答

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

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

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

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

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

hasOwnProperty()方法返回一个布尔值,指示对象是否将指定的属性作为自己的属性(而不是继承它)。

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

console.log(object1.hasOwnProperty('toString'));
// expected output: false

console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false

了解更多信息

您可以使用以下方法-

var obj = {a:1}
console.log('a' in obj)               // 1
console.log(obj.hasOwnProperty('a'))  // 2
console.log(Boolean(obj.a))         // 3

以下方法之间的区别如下-

在第一和第三种方法中,我们不仅搜索对象,还搜索其原型链。如果对象没有该属性,但该属性存在于其原型链中,则该对象将为true。

变量obj={a: 2,__原型__:{b:2}}console.log(obj中的'b')console.log(布尔(obj.b))

第二种方法只检查其自身的财产。示例-

变量obj={a: 2,__原型__:{b:2}}console.log(obj.hasOwnProperty('b'))

第一种方法和第三种方法的区别在于,如果有一个属性的值未定义,则第三种方式将为false,而第一种方法将为true。

变量obj={b:未定义}console.log(布尔(obj.b))console.log(obj中的'b');

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