JavaScript-Map()增量值 [英] JavaScript - Map() increment value

查看:102
本文介绍了JavaScript-Map()增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的地图如下:

let map = new Map();
map.set("a", 1);
//Map is now {'a' => 1}

我想将a的值更改为2,或将其递增:map.get("a")++;

I want to change the value of a to 2, or increment it: map.get("a")++;

当前,我正在使用以下内容:

Currently, I am using the following:

map.set("a", (map.get("a"))+1);

但是,这感觉不对.有谁知道一种更清洁的方式吗?有可能吗?

However, this does not feel right. Does anyone know a cleaner way of doing this? Is it possible?

推荐答案

您的方法很好.如果要使用原始值,则需要这样做.如果要避免调用map.set,则必须恢复为 reference 的值.换句话说,那么您需要存储一个对象,而不是原始对象:

The way you do it is fine. That is how you need to do it if you are working with primitive values. If you want to avoid the call to map.set, then you must revert to a reference to a value. In other words, then you need to store an object, not a primitive:

let map = new Map();
map.set("a", {val: 1});

然后递增变为:

map.get("a").val++;

这篇关于JavaScript-Map()增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆