JavaScript - Map() increment value

前端 未结 5 1449
说谎
说谎 2021-01-07 18:53

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

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 19:38

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

提交回复
热议问题