Javascript对象增量项(如果不存在)
问题描述:
有没有标准的方法来做到这一点?我知道如何在Python中但是在Javascript中最好的方法是通过首先检查密钥是否已经存在来向字典添加密钥,如果没有,则添加值为1,如果它存在则只增加当前计数。
Is there a standard way to do this? I know how in Python but in Javascript whats the best way to add a key to a dictionary by first checking if the key already exists, if not, add it with a value of 1, if it DOES exist then just increment the current count.
像这样的伪代码:
var dict = {};
var new_item = "Bill"
If new_item not in dict:
dict[new_item] = 1
else:
dict[new_item] += 1
答
怎么样这个?
dict[key] = (dict[key] || 0) + 1;