JavaScript-Map()增量值

问题描述:

我的地图如下:

let map = new Map();
map.set("a", 1);
//Map is now {'a' => 1}

我想将a的值更改为2,或将其递增:map.get("a")++;

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?

您的方法很好.如果要使用原始值,则需要这样做.如果要避免调用map.set,则必须恢复为 reference 的值.换句话说,那么您需要存储一个对象,而不是原始对象:

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});

然后递增变为:

map.get("a").val++;