如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
当前回答
您需要使用方法object.hasOwnProperty(属性)。如果对象具有该属性,则返回true,如果对象没有,则返回false。
其他回答
显示如何使用此答案
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
我们也可以使用indexOf,我更喜欢includes
使用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
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)
有关详细信息,请查看此处。
以下是针对特定情况的另一个选项。:)
如果要测试对象上的成员,并想知道它是否已设置为以下以外的值:
''假的无效的未定义0...
那么您可以使用:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
也可以使用ES6 Reflect对象:
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
Reflect.has的MDN文档可在此处找到。
静态Reflect.has()方法的工作方式类似于函数中的in运算符。