迹忆客 专注技术分享

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

JavaScript 中的 Hashmap 等效形式

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

Hashmap 也称为哈希表,是元素的集合,其中元素以键值对的形式存储。当时没有预定义的数据结构可用于用 JavaScript 编程语言实现的 hashmap。不像其他编程语言,如 C++ 或 Java,这种数据结构已经在实现。因为人们过去常常寻找实现 hashmap 的各种替代方案,而大多数时候,他们习惯于使用对象,因为它们也具有 key-value 的结构。

在 JavaScript 的 ES6 版本中,JavaScript 社区引入了一种新的数据结构来实现称为 Map 对象的哈希映射,它是一个键值对。让我们看看如何使用 Map 对象实现一个 hashmap,并使用一些预定义的方法执行各种操作,如插入、删除和更新。

正如我们已经看到的,Map 对象是一个键值对。最初,Map 将为空;里面不会有任何元素。hashmap 中的键可以是字符串或 symbol 类型,hashmap 的值可以是任何类型。

要创建 Map,你可以创建它的一个对象并将其存储在一个变量中,在本例中为 hashmap。现在为了在 hashmap 中插入键值对,JavaScript 提供了一个名为 set() 的方法。这个方法有两个参数,第一个是 key,第二个是 value。在我们创建的 hashmap 中,我们将插入四个元素,每个元素都有一个不同类型的值,如整数、数组、字符串和整个函数。下面是演示相同内容的代码。

var hashmap = new Map();

hashmap.set('1', 700);
hashmap.set('2', [1,2,3]);
hashmap.set('3', "This is a string");
hashmap.set('4', ()=>{console.log("Hello World")});

console.log(hashmap);

运行上面的代码后,这就是它在控制台中的样子。

创建_hashmap

如你所见,我们插入了各种数据类型,包括作为哈希映射值的整个函数。

我们已经创建了一个哈希图;让我们尝试打印哈希图中存在的所有值。它可以在 forEach 循环的帮助下完成。

hashmap.forEach(element => {
    document.write('<br>'+element);
});

使用 document.write() 方法,此输出将直接显示在屏幕上,而不是在控制台内。

在 javascript hashmap 中打印元素

现在让我们使用 has() 方法检查哈希图中是否存在键 3。如果键存在于散列图中,我们将使用 set() 方法更改或替换键 ‘3’ 的现有值。

if(hashmap.has('3')){
    hashmap.set('3', "We changed the value...")
}

console.log(hashmap);

输出:

update_value_hashmap

最后,要从哈希图中删除元素,你可以使用 delete() 方法并传递要删除的相应键。如果你想一次从哈希图中删除所有元素并将其清空,你可以使用 clear() 方法,如下所示。

// deletes 4th element
hashmap.delete("4");
console.log(hashmap);

// clears entire hashmap
hashmap.clear();
console.log(hashmap);

以下是上述代码的输出。

delete_elements_from_hashmap

这是在 JavaScript 中创建哈希映射的等效且正确的方法。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便