如何将一张地图复制到另一张地图?

2022-08-30 04:41:54

如何在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(); 

答案 1

随着JavaScript中Maps的引入,考虑到构造函数接受可迭代,这很简单:

var newMap = new Map(existingMap)

此处的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map


答案 2

一种简单的方法(执行浅层复制)是将源映射的每个属性复制到目标映射:

var newMap = {};
for (var i in myMap)
   newMap[i] = myMap[i];

注意:newMap[i] 很可能是对与 myMap[i] 相同的对象的引用