JavaScript - Map() increment value

柔情痞子 提交于 2020-05-23 05:47:22

问题


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?


回答1:


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++;



回答2:


According to the ECMAScript® 2015 Language Specification states, Map manipulation is based prototypes and the prototype methods assigned to add or retrieve data to or from a Map are the set and get methods respectively.

Except for the unnecessary parenthesis around your map.get("a"), your code is perfectly okay. That's how the Map is meant to be used. If you are looking for something that "may" reduce the length of your code and if it does works for your specific requirement, you may use the JavaScript Object.

So dear, your code is just the same as this:

map.set("a", map.get("a")+1);



回答3:


Map#get returns the value of the specified element. It is opposite of an object accessor (object['a']) and is not eligible for a left-hand side assignment.

The conclusion is to use always Map#set for setting a new value.




回答4:


I don't know any cleaner way to do that, nevertheless I think that everything depends from the context of your code.

If you are iterating an array or something else and you want to increase your variable, I suggest to use a local variable to do that and, at the end of the iteration, set the value in the map.

var i = map.get('a')

values.forEach( el => {
  i += el.someField
})

map.set('a', i)


来源:https://stackoverflow.com/questions/53584369/javascript-map-increment-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!