javascript - 更改 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')))
怎么了 ?
解决方案
因为键 2 包含一个对象。创建新地图时,它会复制对象引用,并且不会真正创建深层副本。唯一重复的是对该对象所在地址的引用。其他值是原语,默认情况下深度重复
推荐阅读
- flutter - 为什么这个“StreamBuilder”使用之前关闭的流中的数据?
- c# - StartCoroutine 仅适用于超过 1 个对象,如果它在游戏启动时启动
- c++ - 复合辛普森规则代码不断得到错误的输出?
- reactjs - 如何在父级的 setInterval 中调用子级中的函数?
- sql - 基于 SQL 上面的行计算的列值
- android - 如何从 SeekBar kotlin 获取输入
- c# - Windows Form应用程序关闭或停止响应时如何自动关闭selenium chromedriver?
- authentication - 使用 URL 验证和访问 APEX 应用程序页面
- python - 如何在python中读取多个大的.jsonl文件
- bash - Bash 配置文件语法错误:文件意外结束