How to increment a value in a JavaScript object?

前端 未结 7 1007
时光说笑
时光说笑 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 13:55

    You can check if the object doesn't have the specific key and set it or increase existing key value by one:

    function assignKey(obj, key) {
      typeof obj[key] === 'undefined' ? obj[key] = 1 : obj[key]++;
    }
    
    var map = {};
    
    assignKey(map, 2);
    assignKey(map, 2);
    assignKey(map, 4);
    assignKey(map, 1);
    assignKey(map, 2);
    assignKey(map, 5);
    assignKey(map, 1);
    console.log(map);

提交回复
热议问题