迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中的 hasOwnProperty

作者:迹忆客 最近更新:2023/03/10 浏览次数:

我们经常看到关于 in 惯例和 hasOwnProperty 的两难境地,但在特定情况下两者的工作方式不同。主要概念是 in 适用于具有继承属性并导致 true 的对象,而 hasOwnProperty 仅对未继承而是显式定义的属性返回 true。

在这里,我们将只讨论 JavaScript 中的 hasOwnProperty

在 JavaScript 中,检查属性是否定义的结构是这样的 - objectName.hasOwnProprty(property)。在这里,一个对象可以是一个数组,也可以是一个键值对。你可以检查定向路径

数组从 0 开始索引,直到最后一个可用元素。因此,我们更喜欢使用索引值来调用数组对象的属性。下面的例子给出了一个清晰的思路。

代码片段:

var myObj = ["Liza", "Kary", "Blake"];

console.log(myObj.hasOwnProperty(2));
console.log(myObj.hasOwnProperty(3));

输出:

javascript 中数组的 hasownprop

在这方面,我们将考虑一个具有键值(string)和属性(任何数据类型)的字典。我们来看下面的例子:

代码片段:

输出:

javascript 中 obj 的 hasownprop

如你所见,对象 myObj 只有两个键 - petage。如果我们通过 hasOwnProperty 仅调用这两个属性,我们将看到控制台结果 true。否则,我们调用随机属性 color,结果为 false

JavaScript ES6 有一个额外的特性 class,使用 constructor 可以定义一些动态对象。在声明对象之后,你可以通过为它们定义值来轻松访问它们。演示将清除本节的解释。此外,对于任何自定义值,如果属性存在于类构造函数中,你将得到答案 true;否则,

代码片段:

class pet{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

const pet1 = new pet("Izequel", 5);

console.log(pet1.hasOwnProperty("name"));
console.log(pet1.hasOwnProperty("color"));

javascript 中类的 obj 的 hasOwnprop

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便