首页 > 解决方案 > 更改 Map 中的值也会在另一个 Map 上更改

问题描述

编辑:标记为重复的问题,但重复的帖子并没有帮助我解决这个问题。如何修改 map2 的值而不更改 map1 的值?(JavaScript 是按引用传递还是按值传递语言?

我有2张地图。第一个可以被认为是在加载页面时初始化的“事实来源”。我想将第一张地图的内容复制到第二张地图中。所以我的所有更改都将应用于第二张地图,如果我想恢复我的更改,我将使用我的第一个。

但是复制一张地图是一个奇怪的错误的原因,当第二张地图改变时,它会改变第一张地图的内容。

var map1 = new Map()
var map2 = new Map()

map1.set('1', 'one')
map1.set('2', {alpha:"NOT",beta:"MODIFIED"})
map1.set('3', 'three')
    
// Duplicate the content of the first map into the second one //
map2 = new Map(map1) //<-- this is probably because of that assignment 
    
var x = map2.get('2')
x.alpha = "why???"
x.beta = "how???"
//Why does the value of the map change when I edit the 'x' variable ?
// map2.set('2', x); is not required ?

console.log("MAP1 : " + JSON.stringify(map1.get('2')))
console.log("MAP2 : " + JSON.stringify(map2.get('2')))

但是片段效果很好,不会修改第一个地图的值(但我不能用这种方法只修改 map2 内的一部分内容)

var map1 = new Map()
var map2 = new Map()

map1.set('1', 'one')
map1.set('2', {alpha:"NOT",beta:"MODIFIED"})
map1.set('3', 'three')
    
// Duplicate the content of the first map into the second one //
map2 = new Map(map1) //<-- this is probably because of that assignment 
    
map2.set('2', {alpha:'but this', beta:'work ???'})

console.log("MAP1 : " + JSON.stringify(map1.get('2')))
console.log("MAP2 : " + JSON.stringify(map2.get('2')))

怎么了 ?

标签: javascript

解决方案


因为键 2 包含一个对象。创建新地图时,它会复制对象引用,并且不会真正创建深层副本。唯一重复的是对该对象所在地址的引用。其他值是原语,默认情况下深度重复


推荐阅读