Javascript对象增量项(如果不存在)

编程入门 行业动态 更新时间:2024-10-25 16:18:14
本文介绍了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对象增量项(如果不存在)

本文发布于:2023-10-07 10:35:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   增量   对象   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!