如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
当前回答
以下是针对特定情况的另一个选项。:)
如果要测试对象上的成员,并想知道它是否已设置为以下以外的值:
''假的无效的未定义0...
那么您可以使用:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
其他回答
显示如何使用此答案
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
以下是针对特定情况的另一个选项。:)
如果要测试对象上的成员,并想知道它是否已设置为以下以外的值:
''假的无效的未定义0...
那么您可以使用:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
另一种相对简单的方法是使用Object.keys。这将返回一个数组,这意味着您将获得数组的所有特性。
var noInfo = {};
var info = {something: 'data'};
Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true
尽管我们身处一个拥有强大浏览器支持的世界。因为这个问题太老了,我想我应该补充一下:从JavaScript v1.8.5开始,这是安全的。
好吧,看来我的答案是正确的,除非你不想继承财产:
if (x.hasOwnProperty('key'))
以下是包含继承财产的其他选项:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)