如何检查对象在JavaScript中是否具备特定属性? javascript
考虑: java
x = {'key': 1}; if ( x.hasOwnProperty('key') ) { //Do this }
那是最好的方法吗? 安全
随着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
是的,它是:)我想您也能够执行Object.prototype.hasOwnProperty.call(x, 'key')
,若是x
具备一个名为hasOwnProperty
的属性,它也应该能够工做:) spa
但这会测试本身的属性。 若是要检查它是否具备也能够继承的属性,能够使用typeof x.foo != 'undefined'
。 prototype
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 Rudolph和Armin Ronacher 指出 ,一种更安全但较慢的解决方案是: 对象
Object.prototype.hasOwnProperty = function(property) { return typeof this[property] !== 'undefined'; };
好的,除非您不想继承属性,不然个人答案彷佛正确:
if (x.hasOwnProperty('key'))
如下是一些其余选项来包含继承的属性:
if (x.key) // Quick and dirty, but it does the same thing as below. if (x.key !== undefined)
if (typeof x.key != "undefined") { }
由于
if (x.key)
若是x.key
解析为false
则失败(例如, x.key = ""
)。