In JavaScript, you can use an object to create a simple hash table. Here are a few ways to populate a hash table:
- Create an empty object and add key-value pairs using the object literal syntax:
let myHashTable = {};
myHashTable["key1"] = "value1";
myHashTable["key2"] = "value2";
- Use the Object.assign() method to add multiple key-value pairs to an existing object:
let myHashTable = {};
Object.assign(myHashTable, {"key1": "value1", "key2": "value2"});
- Use a loop to add key-value pairs to the object:
let myHashTable = {};
for (let i = 0; i < 5; i++) {
myHashTable["key" + i] = "value" + i;
}
- You can also use the Map object to create a more sophisticated hash table. Here’s an example:
let myHashTable = new Map();
myHashTable.set("key1", "value1");
myHashTable.set("key2", "value2");
The Map object allows you to use any data type as the key, not just strings like with the object method.
+ There are no comments
Add yours