How to increment a value in a JavaScript object?

前端 未结 7 1193
时光说笑
时光说笑 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:58

    It would be better if you convert array's value into integer and increment it. It will be robust code. By default array's value is string. so in case you do not convert it to integer then it might not work cross browser.

    if (map[key] == null) map[key] = 0;
    map[key] = parseInt(map[key])+1;
    

提交回复
热议问题