如何将地图复制到复制地图中?

2022-04-08 00:00:00 clone object node.js javascript

如何在JavaScript中克隆/复制地图?

我知道如何克隆阵列,但如何克隆/复制映射?

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(); 

解决方案

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

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

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

相关文章