如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
当前回答
2022年更新
Object.hasOwn()
建议使用Object.hasOwn()而不是Object.hasOwnerProperty(),因为它适用于使用Object.create(null)创建的对象以及已重写继承的hasOwnProperty()方法的对象。虽然可以通过对外部对象调用Object.pr原型.hasOwnProperty()来解决这些问题,但Object.hasOwn()更直观。
实例
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
原答覆
我真的被给出的答案弄糊涂了——大多数答案都是完全错误的。当然,您可以拥有具有未定义、null或false值的对象财产。因此,简单地将属性检查减少为this〔property〕的类型,或者更糟糕的是,x.key将给您带来完全误导的结果。
这取决于你要找什么。如果你想知道一个对象是否在物理上包含一个属性(并且它不是来自原型链上的某个地方),那么object.hasOwnProperty就是最好的方法。所有现代浏览器都支持它。(Safari 2.0.1和更早版本中缺少它,但这些版本的浏览器很少再使用了。)
如果您要查找的是一个对象上是否有可迭代的属性(当您迭代对象的财产时,它就会出现),那么在对象中执行:prop将获得您想要的效果。
由于使用hasOwnProperty可能是您想要的,并且考虑到您可能需要回退方法,我向您介绍了以下解决方案:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
以上是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)
有关详细信息,请查看此处。
if(x.hasOwnProperty("key")){
// …
}
因为
if(x.key){
// …
}
如果x.key错误(例如,x.key==“”),则失败。
您需要使用方法object.hasOwnProperty(属性)。如果对象具有该属性,则返回true,如果对象没有,则返回false。
是的,它是:)我想你也可以做Object.protype.hasOwnProperty.call(x,'key'),如果x有一个名为hasOwnProperty:)的属性,这也应该有效
但这是对自身财产的测试。如果你想检查它是否有一个属性也可能是固有的,你可以使用typeof x.foo!='未定义”。
x?。如果x.key存在,key返回1,否则未定义