如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
当前回答
显示如何使用此答案
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
我们也可以使用indexOf,我更喜欢includes
其他回答
您需要使用方法object.hasOwnProperty(属性)。如果对象具有该属性,则返回true,如果对象没有,则返回false。
对象上存在一个方法“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”));
让我们在这里消除一些困惑。首先,让我们通过假设hasOwnProperty已经存在来简化;目前使用的绝大多数浏览器都是如此。
如果传递给它的属性名已添加到对象中,hasOwnProperty返回true。它完全独立于分配给它的实际值,而实际值可能完全未定义。
因此:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
然而:
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
问题是当原型链中的对象具有值为undefined的属性时会发生什么?hasOwnProperty将为false,也将为false!==未定义。然而,对于。。中仍将在枚举中列出它。
最重要的是,没有跨浏览器的方法(因为Internet Explorer不公开__prototype__)来确定特定标识符是否未附加到对象或其原型链中的任何内容。
使用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
x?。如果x.key存在,key返回1,否则未定义