我确信这应该很容易解决,但我无法弄清楚。 我有一个 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/