How to increment a value in a JavaScript object?

前端 未结 7 1011
时光说笑
时光说笑 2021-02-12 13:50
var map = {};
map[key] = value;

How can I

  • assign value 1 if key does not yet exist in the object
  • increment the value by 1 if it
7条回答
  •  不知归路
    2021-02-12 14:03

    function addToMap(map, key, value) {
        if (map.has(key)) {       
            map.set(key, parseInt(map.get(key), 10) + parseInt(value, 10));
        } else {
            map.set(key, parseInt(value, 10));
        }       
    }
    

提交回复
热议问题