浅层克隆映射或集

2022-08-30 03:05:29

如何在 JavaScript 中浅层克隆 MapSet 对象?

我想获取具有相同键和值的新地图或集。


答案 1

使用构造函数克隆映射和集:

var clonedMap = new Map(originalMap)

var clonedSet = new Set(originalSet)

答案 2

浅克隆:

var clonedMap = new Map(originalMap)

var clonedSet = new Set(originalSet)

深度克隆:

var deepClonedMap = new Map(JSON.parse(JSON.stringify([...originalMap])))
var deepClonedSet = new Set(JSON.parse(JSON.stringify([...originalSet])))

let originalMap = new Map()
let data = {a:'a',b:'b'}
originalMap.set(1,data)

let shallowCloned = new Map(originalMap)
let deepCloned = new Map(JSON.parse(JSON.stringify([...originalMap])))
data.a = 'p'
console.log('originalMap:',[...originalMap])
console.log('shallowCloned:',[...shallowCloned])
console.log('deepCloned:',[...deepCloned])