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

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

考虑: java

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

那是最好的方法吗? 安全


#1楼

随着Underscore.js或( 甚至更好lodash测试

_.has(x, 'key');

该方法调用Object.prototype.hasOwnProperty ,但(a)的类型较短,而且(b)使用“对hasOwnProperty的安全引用”(即,即便hasOwnProperty被覆盖也能够使用)。 ui

特别是lodash将_.has定义为: this

function has(object, key) {
      return object ? hasOwnProperty.call(object, key) : false;
   }
   // hasOwnProperty = Object.prototype.hasOwnProperty

#2楼

是的,它是:)我想您也能够执行Object.prototype.hasOwnProperty.call(x, 'key') ,若是x具备一个名为hasOwnProperty的属性,它也应该能够工做:) spa

但这会测试本身的属性。 若是要检查它是否具备也能够继承的属性,能够使用typeof x.foo != 'undefined'prototype


#3楼

if (x.key !== undefined)

Armin Ronacher彷佛已经击败了我 ,可是: code

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 RudolphArmin Ronacher 指出 ,一种更安全但较慢的解决方案是: 对象

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

#4楼

好的,除非您不想继承属性,不然个人答案彷佛正确:

if (x.hasOwnProperty('key'))

如下是一些其余选项来包含继承的属性:

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

if (x.key !== undefined)

#5楼

if (typeof x.key != "undefined") {

}

由于

if (x.key)

若是x.key解析为false则失败(例如, x.key = "" )。

相关文章
相关标签/搜索