如何检查对象在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
了解更多信息
其他回答
好吧,看来我的答案是正确的,除非你不想继承财产:
if (x.hasOwnProperty('key'))
以下是包含继承财产的其他选项:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
hasOwnProperty“可用于确定对象是否具有指定的属性作为该对象的直接属性;与in运算符不同,此方法不检查对象的原型链。”
因此,最有可能的是,根据您的问题,您不想使用hasOwnProperty,它确定属性是否直接附加到对象本身,。
如果要确定该属性是否存在于原型链中,可以使用如下方式:
if (prop in object) { // Do something }
x?。如果x.key存在,key返回1,否则未定义
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';
};
如果您正在搜索属性,请选择“否”。您需要:
if ('prop' in obj) { }
通常,您不应该关心属性是否来自原型或对象。
然而,因为您在示例代码中使用了“key”,所以看起来您将对象视为哈希,在这种情况下,您的答案是有意义的。所有散列键都是对象中的财产,您可以避免原型提供额外的财产。
约翰·雷格的回答很全面,但我认为不清楚。特别是当在obj中使用“rop”时。