如何将一张地图复制到另一张地图?
如何在 JavaScript 中克隆/复制 Map
?
我知道如何克隆数组,但如何克隆/复制 Map
?
var myArray = new Array(1, 2, 3);
var copy = myArray.slice();
// now I can change myArray[0] = 5; & it wont affect copy array
// Can I just do the same for map?
var myMap = new ?? // in javascript is it called a map?
var myMap = {"1": 1, "2", 2};
var copy = myMap.slice();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
随着 JavaScript 中地图的引入,考虑到构造函数接受可迭代,这非常简单:
此处的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
With the introduction of Maps in JavaScript it's quite simple considering the constructor accepts an iterable:
Documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
一种简单的方法(进行浅复制)是将源映射的每个属性复制到目标映射:
A simple way (to do a shallow copy) is to copy each property of the source map to the target map:
如果您需要制作 Map 的深层副本,可以使用以下命令:
其中
source
是原始 Map 对象。请注意,这可能并不适合 Map 值不可序列化的所有用例,有关更多详细信息,请参阅:https://stackoverflow.com /a/122704/10583071
If you need to make a deep copy of a Map you can use the following:
Where
source
is the original Map object.Note this may not be suitable for all use cases where the Map values are not serializable, for more details see: https://stackoverflow.com/a/122704/10583071
非常简单,只需使用
Object.assign()
Very simple to just use
Object.assign()
JQuery 有一个方法来扩展一个对象(合并两个对象),但是这个方法也可以用于通过提供一个空对象来克隆一个对象。
更多信息可以在jQuery 文档中找到。
JQuery has a method to extend an object (merging two objects), but this method can also be used to clone an object by providing an empty object.
More information can be found in the jQuery documentation.
没有内置任何内容。
要么使用经过良好测试的递归属性复制器,要么如果性能不是问题,则序列化为 JSON 并再次解析为新对象。
There is nothing built in.
Either use a well tested recursive property copier or if performance isn't an issue, serialise to JSON and parse again to a new object.
没有内置(编辑:DEEP)克隆/复制。您可以编写自己的方法来
浅复制或深复制:[编辑]浅复制是内置的,使用
Object.assign
:全部Javascript 中的对象是动态的,并且可以分配新的属性。您所指的“地图”实际上只是一个空对象。数组也是一个对象,具有
slice
等方法和length
等属性。There is no built-in (edit: DEEP) clone/copy. You can write your own method to
either shallow ordeep copy:[EDIT] Shallow copy is built-in, using
Object.assign
:All objects in Javascript are dynamic, and can be assigned new properties. A "map" as you refer to it is actually just an empty object. An Array is also an object, with methods such as
slice
and properties likelength
.我注意到 Map 应该需要特殊处理,因此根据该线程中的所有建议,代码将是:
I noticed that Map should require special treatment, thus with all suggestions in this thread, code will be: