JavaScript - Map() increment value

前端 未结 5 1555
说谎
说谎 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:32

    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)
    

提交回复
热议问题