如何检查对象在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”));

其他回答

另一种相对简单的方法是使用Object.keys。这将返回一个数组,这意味着您将获得数组的所有特性。

var noInfo = {};
var info = {something: 'data'};

Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true

尽管我们身处一个拥有强大浏览器支持的世界。因为这个问题太老了,我想我应该补充一下:从JavaScript v1.8.5开始,这是安全的。

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

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

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

那么您可以使用:

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

JavaScript现在正在发展壮大,因为它现在有好的甚至有效的方法来检查它。

以下是检查对象是否具有特定属性的一些简单方法:

使用hasOwnProperty()

const hero = {
  name: 'Batman'
};

hero.hasOwnProperty('name');     // => true
hero.hasOwnProperty('realName'); // => false

在中使用关键字/运算符

const hero = {
  name: 'Batman'
};

'name' in hero;     // => true
'realName' in hero; // => false

与未定义的关键字比较

const hero = {
  name: 'Batman'
};

hero.name;     // => 'Batman'
hero.realName; // => undefined

// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)

有关详细信息,请查看此处。

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 isProperty =  (objectname.keyname || "") ? true : false;

对于大多数情况来说,这是简单明了的。。。