如何在 Angular 4+ 中更新地图现有键的值

Vit*_*han 1 dictionary angular angular6

有什么方法可以更新 angular 4+ 中创建的键值对映射的值。

说我有:

testMap: Map<number, string> = new Map<number, string>();

ngOnInit() {
    this.testMap.set(1, "A");
    this.testMap.set(2, "B");
    this.testMap.set(3, "C");
    this.testMap.set(4, "D");
    this.testMap.set(5, "E");
}

changeValue(id){
    //id is the one of the keys of the map whose value needs to be altered
    //let say (id=3)
    this.testMap.put(id,"ChangedValue"); //PUT is from java
}
Run Code Online (Sandbox Code Playgroud)

小智 9

你可以只设置:

this.testMap.set(id, "ChangedValue")
Run Code Online (Sandbox Code Playgroud)

  • 如果您想更新 Map 中某个对象的属性,您所需要做的就是获取该对象并更改该属性。`const obj = myMap.get(key); obj.name = "new name";` 就是这样,该对象是通过引用的,因此它将自动反映在存储在 Map 中的条目中。 (3认同)