Object.hasOwnProperty()
方法用于检查对象是否拥有指定的属性。
示例
const obj = {};
obj.id = 42;
// check if id is present in obj or not
console.log(obj.hasOwnProperty("id"));
// Output: true
hasOwnProperty() 语法
hasOwnProperty()
方法的语法是
obj.hasOwnProperty(prop)
其中,obj 是我们要搜索属性的对象。
由于这是一个静态方法,我们需要使用类名 Object
来访问 hasOwnProperty()
。
hasOwnProperty() 参数
hasOwnProperty()
方法接受
hasOwnProperty() 返回值
getPrototypeOf()
方法返回一个 布尔值
true
- 如果对象拥有指定的属性false
- 如果对象不拥有指定的属性
注意事项
- 与
in
操作符不同,此方法不会检查对象原型链中的属性。 - 即使属性的值是
null
或undefined
,hasOwnProperty()
也会返回true
。
示例:Javascript Object.hasOwnProperty()
// create an object with property id
const obj = {id: 42};
// check if id exists in obj
console.log(obj.hasOwnProperty("id"));
// Output: true
// check if name exists in obj
console.log(obj.hasOwnProperty("name"));
// Output: false
// inherited properties return false
console.log(obj.hasOwnProperty("toString"));
// Output: false
在上面的示例中,我们创建了一个名为 obj 的对象,其中包含一个属性 id。
然后,我们使用 hasOwnProperty()
方法检查 obj 是否拥有 id 和 name 属性。
输出表明该对象拥有 id 属性,但没有 name 属性。
最后,我们使用 hasOwnProperty()
检查 toString 是否在对象中定义。
然而,尽管 toString
是 JavaScript 中所有对象的属性,我们仍然得到 false
的输出。
这是因为 toString
是一个继承的属性,而不是对象本身直接定义的属性。
另请阅读