I have a map as follows:
let map = new Map(); map.set("a", 1); //Map is now {'a' => 1}
I want to change the value of a
to 2, or increment it: map.get("a")++;
Currently, I am using the following:
map.set("a", (map.get("a"))+1);
However, this does not feel right. Does anyone know a cleaner way of doing this? Is it possible?
The Map. entries() method does not require any argument to be passed and returns an iterator object of the map. Applications: Whenever we want to get all the [key, value] pairs of each element of a map using an iterator object, we use the Map. entries() method.
To increment a value in an object, assign the value of the key to the current value + 1, e.g. obj. num = obj. num +1 || 1 . If the property exists on the object, its value gets incremented by 1 , and if it doesn't - it gets initialized to 1 .
To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.
JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.
The way you do it is fine. That is how you need to do it if you are working with primitive values. If you want to avoid the call to map.set
, then you must revert to a reference to a value. In other words, then you need to store an object, not a primitive:
let map = new Map(); map.set("a", {val: 1});
And then incrementing becomes:
map.get("a").val++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With