如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
当前回答
hasOwnProperty()方法返回一个布尔值,指示对象是否将指定的属性作为自己的属性(而不是继承它)。
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
了解更多信息
其他回答
是的,它是:)我想你也可以做Object.protype.hasOwnProperty.call(x,'key'),如果x有一个名为hasOwnProperty:)的属性,这也应该有效
但这是对自身财产的测试。如果你想检查它是否有一个属性也可能是固有的,你可以使用typeof x.foo!='未定义”。
hasOwnProperty()方法返回一个布尔值,指示对象是否将指定的属性作为自己的属性(而不是继承它)。
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
了解更多信息
以下是针对特定情况的另一个选项。:)
如果要测试对象上的成员,并想知道它是否已设置为以下以外的值:
''假的无效的未定义0...
那么您可以使用:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
给定myObject对象和“myKey”作为密钥名称:
Object.keys(myObject).includes('myKey')
or
myObject.hasOwnProperty('myKey')
or
typeof myObject.myKey !== 'undefined'
最后一个被广泛使用,但(正如其他答案和评论中所指出的)它也可以匹配从Object原型派生的键。
if (x.key !== undefined)
Armin Ronacher似乎已经击败了我,但是:
Object.prototype.hasOwnProperty = function(property) {
return this[property] !== undefined;
};
x = {'key': 1};
if (x.hasOwnProperty('key')) {
alert('have key!');
}
if (!x.hasOwnProperty('bar')) {
alert('no bar!');
}
康拉德·鲁道夫(Konrad Rudolph)和阿明·罗纳彻(Armin Ronacher)指出,一个更安全但更慢的解决方案是:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};