Javascript对象增量项(如果不存在) [英] Javascript Object increment item if not exist
本文介绍了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;
这篇关于Javascript对象增量项(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文