JavaScript Object.hasOwnProperty()


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 操作符不同,此方法不会检查对象原型链中的属性。
  • 即使属性的值是 nullundefinedhasOwnProperty() 也会返回 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 是否拥有 idname 属性。

输出表明该对象拥有 id 属性,但没有 name 属性。

最后,我们使用 hasOwnProperty() 检查 toString 是否在对象中定义。

然而,尽管 toString 是 JavaScript 中所有对象的属性,我们仍然得到 false 的输出。

这是因为 toString 是一个继承的属性,而不是对象本身直接定义的属性。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战