📜  javascript hashmap - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:05.330000             🧑  作者: Mango

JavaScript HashMap

A HashMap is a data structure that maps keys to values. In JavaScript, it can be implemented using an object.

Creating a HashMap

To create a HashMap in JavaScript, you can simply declare an object literal and assign values to keys:

const hashMap = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3'
};
Adding and Accessing elements in a HashMap

To add a new element to a HashMap, simply assign a value to a new key:

hashMap['key4'] = 'value4';

To access an element in a HashMap, you can use the key:

const value = hashMap['key1']; // returns 'value1'
Checking if a HashMap has a Key

You can check if a HashMap has a key using the in operator:

const hasKey = 'key1' in hashMap; // returns true
Removing an element from a HashMap

To remove an element from a HashMap, you can use the delete operator:

delete hashMap['key1'];
Iterating over a HashMap

To iterate over the keys in a HashMap, you can use a for...in loop:

for (const key in hashMap) {
  console.log(`${key}: ${hashMap[key]}`);
}

This will output:

key2: value2
key3: value3
key4: value4
Conclusion

HashMaps are an extremely useful data structure in JavaScript that can be implemented easily using an object. They allow you to map keys to values, add and remove elements, and iterate over the keys.