JavaScript 关联数组和哈希表
我们将学习如何使用对象和 Map()
实现 JavaScript 关联数组和哈希表。
尽管 JavaScript 除了对象之外没有关联数组/哈希表。但是还有其他方法可以做到这一点。
在深入了解详细实现之前,有必要了解关联数组、映射、字典和哈希表之间的区别。虽然这些都是用来保存键值对数据的,但还是有区别的。
- 关联数组是一种数据结构概念,包含(键、值)对中的数据。它也被称为抽象数据类型,就像 Map 和字典一样。这里的索引是字符串,而不是整数。有不同的方法来实现关联数组;哈希表就是其中之一。
- 字典还保存(键,值)对中的数据,与关联数组相同。但是,它的索引是整数。
- Map 也有键值对的数据。它会记住键的原始插入顺序。
- 哈希表就是使用哈希方法在内存中排列数据。它是模拟关联数组的方法之一。
使用对象创建 JavaScript 关联数组
// first way to create associative array
const person = [];
person['firstname'] = 'Mehvish';
person['lastname'] = 'Ashiq';
person['age'] = 30;
person['city'] = 'Multan';
person['email'] = 'delfstack@example.com';
// second way to create associative array
const person = {
firstname: 'Mehvish',
lastname: 'Ashiq',
age: 30,
city: 'Multan',
email: 'delfstack@example.com'
};
我们在上面的代码中创建了一个用作关联数组的 JavaScript 对象。firstname
、lastname
、age
、city
和 email
是键(索引)。这些值是 Mehvish
、Ashiq
、30
、Multan
、delfstack@example.com
。
假设我们要添加一个新的键值对作为 phone:12334567
。为此,我们可以使用 Object.assign()
函数。它将第二个对象复制到第一个对象的末尾。
// Here the second object is {phone:12334567}
// Here the first object is person
Object.assign(person, {phone: 12334567});
我们可以通过定位键(索引)来访问每个键的值。请记住,索引是字符串,而不是数字。所以,你不能在这里像 person[0]
一样访问(如果你使用字典,你可以使用 person[0]
)。
// to print in the browser
document.write(person.firstname); // OUTPUT: Mehvish
document.write(person['firstname']); // OUTPUT: Mehvish
document.write(person[0]); // OUTPUT: undefined
// to print on console
console.log(person.firstname); // OUTPUT: Mehvish
console.log(person[0]); // OUTPUT: undefined
我们可以使用 for
循环打印完整的关联数组。
// print complete associative array using for look
for (var key in person) {
var value = person[key];
document.write(value);
document.write(' ');
}
输出:
"[firstname: Mehvish]"
"[lastname: Ashiq]"
"[age: 30]"
"[city: Multan]"
"[email: delfstack@example.com]"
"[phone: 12334567]"
打印整个关联数组的更优化方法是 Object.entries()
方法,它采用对象数据类型的一个参数。你可以阅读 this 了解更多 Object 的功能。
// print complete associative array using for look
let completeAssociateArray = Object.entries(person);
console.log(completeAssociateArray);
输出:
[["firstname", "Mehvish"], ["lastname", "Ashiq"], ["age", 30], ["city", "Multan"], ["email", "delfstack@example.com"], ["phone", 12334567]]
使用 Map()
函数创建 JavaScript 关联数组
// first way to create associative array using Map function
const person = new Map();
person.set('firstname', 'Mehvish');
person.set('lastname', 'Ashiq');
person.set('age', 30);
person.set('city', 'Multan');
person.set('email', 'delfstack@example.com');
// second way to create associative array using Map function
const person = new Map([
['firstname', 'Mehvish'], ['lastname', 'Ashiq'], ['age', 30],
['city', 'Multan'], ['email', 'delfstack@example.com']
]);
使用 get(key)
方法,我们可以获得一个特定的值。
person.get('city'); // output is "Multan"
显示整个关联数组键值对。
for (const [key, value] of person.entries()) {
console.log(key + ' = ' + value)
}
输出:
"firstname = Mehvish"
"lastname = Ashiq"
"age = 30"
"city = Multan"
"email = delfstack@example.com"
使用 keys()
函数仅打印键。
for (const key of person.keys()) {
console.log(key)
}
输出:
"firstname"
"lastname"
"age"
"city"
"email"
仅使用 values()
函数获取值。
for (const value of person.values()) {
console.log(value)
}
输出:
"Mehvish"
"Ashiq"
30
"Multan"
"delfstack@example.com"
我们可以使用 delete(key)
删除一个元素;如果成功删除,则返回 true
。如果元素与给定键相关联,则 has(key)
返回 true
,而 clear()
删除所有键值对。
如需详细了解,你可以访问这页面。如果你正在寻找哈希表的实现,你可以使用 Map() 函数,但我们使用 JavaScript 对象来实现哈希表。
使用 JavaScript 对象实现哈希表
var ht = new HashTable({firstname: 'Mehvish', lastname: 'Ashiq', age: 30});
function HashTable(person) {
this.size = 0;
this.item = {};
for (var p in person) {
if (person.hasOwnProperty(p)) {
this.item[p] = person[p];
this.size++;
}
}
this.set =
function(key, value) {
var previousItem = undefined;
if (this.has(key)) {
previousItem = this.item[key];
} else {
this.size++;
}
this.item[key] = value;
return previousItem;
}
this.get =
function(key) {
return this.has(key) ? this.item[key] : undefined;
}
this.has = function(key) {
return this.item.hasOwnProperty(key);
}
}
让我们使用以下代码对其进行测试。
console.log(ht.size);
console.log(ht.get('firstname'));
它给出了以下结果。
3
"Mehvish"
hasOwnProperty
用于检查键是否属于 item
对象。换句话说,如果给定的属性直接属于 item
对象,它返回 true
。
set
、get
和 has
只是 Object 函数的模仿形式。
相关文章
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 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。