Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Add elements to a Dictionary in Javascript
Now we'll create the put method that'll allow us to put key-value pairs on the dictionary. Now using this we'll implement the put method.
Note that JS has objects that act quite like dictionaries. We can just set the container's key property to value.
Example
put(key, value) {
this.container[key] = value;
}
You can test this and the previous functions using −
Example
const myMap = new MyMap()
myMap.put("key1", "value1")
myMap.put("key2", "value2")
myMap.display()
console.log(myMap.hasKey("key1"));
console.log(myMap.hasKey("key3"));
Output
This will give the output −
{key1: "value1", key2: "value2"}
true
false
In ES6, you can put a key-value pair in a map using the set method. For example,
Example
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
myMap.set("key3", "value3")
console.log(myMap.has("key1"))
console.log(myMap.has("key3"))
Output
This will give the output −
True True
Advertisements
