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

考虑:

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

这是最好的方法吗?


当前回答

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

了解更多信息

其他回答

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

if (x.hasOwnProperty('key'))

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

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

if (x.key !== undefined)

给定myObject对象和“myKey”作为密钥名称:

Object.keys(myObject).includes('myKey')

or

myObject.hasOwnProperty('myKey')

or

typeof myObject.myKey !== 'undefined'

最后一个被广泛使用,但(正如其他答案和评论中所指出的)它也可以匹配从Object原型派生的键。

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

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

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

那么您可以使用:

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

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

您可以使用以下方法-

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');