如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在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”));
其他回答
使用Undercore.js或(甚至更好)Lodash:
_.has(x, 'key');
它调用Object.prototype.hasOwnProperty,但(a)比type短,(b)使用“hasOwnProperty的安全引用”(即,即使hasOwnProperty被覆盖,它也能工作)。
特别是,Lodash将_定义为:
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
也可以使用ES6 Reflect对象:
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
Reflect.has的MDN文档可在此处找到。
静态Reflect.has()方法的工作方式类似于函数中的in运算符。
if(x.hasOwnProperty("key")){
// …
}
因为
if(x.key){
// …
}
如果x.key错误(例如,x.key==“”),则失败。
x?。如果x.key存在,key返回1,否则未定义
当你能做到以下几点时,不要过于复杂:
var isProperty = (objectname.keyname || "") ? true : false;
对于大多数情况来说,这是简单明了的。。。