javascript - 如何改变 Map 对象 ES6 中给定键的值

标签 javascript ecmascript-6

我确信这应该很容易解决,但我无法弄清楚。 我有一个 Map 对象,其中包含一组字符串作为键,初始值设置为零。

let n = new Map();
n.set("example1", 0);
n.set("example2", 0);
n.set("example3", 0);

const conditions = () =>{
   let exampStr;
   //random set of conditions
   return exampStr; // can return example1, example2 o example3 
}

// use the result of the function conditions() to add 1 to the value of the map n at the given key. 

我有一个函数,在满足一组条件的情况下,应该++ 某个键的值。我不知道如何通过传递相应的键来更改该映射的给定键的值。

最佳答案

您无法直接更新 Map 中给定键的值。您可以做的就是先获取该值,将其加 1,然后将其重新分配给同一个键:

const key = conditions();
n.set(key, n.get(key) + 1);

关于javascript - 如何改变 Map 对象 ES6 中给定键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61145800/

相关文章:

Javascript - 更改二维数组的名称

javascript - for循环导致 "Unexpected token"错误

JavaScript : What is the difference between these two fat arrow functions?

javascript - 无法在 IIEF 中传递变量

javascript - React Function 在调用 Twice 时更新状态

javascript - (响应式 jQuery)Div 未填充浏览器高度

javascript - 属性更改时 react 动画元素?

javascript - 如何在jquery.localscroll中选择当前点击的 anchor 元素?

javascript - 如何在JavaScript中获取数组中对象的所有键

Javascript更新对象属性值