【问题标题】:How to mutate the value of a given key in a Map object ES6 [duplicate]如何改变Map对象ES6中给定键的值[重复]
【发布时间】:2020-04-10 17:49:35
【问题描述】:

我确信这应该很容易解决,但我想不通。 我有一个 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. 

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

【问题讨论】:

  • n.get()取值,加1,用n.set()保存?你问的是这个吗?

标签: javascript ecmascript-6


【解决方案1】:

您不能直接更新 Map 中给定键的值。您可以做的就是先简单地获取该值,将其递增 1,然后将其重新分配给同一个键:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 2015-12-16
    • 2021-11-04
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多