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