答案 0 :(得分:135)
使用构造函数克隆地图和集:
var clonedMap = new Map(originalMap)
var clonedSet = new Set(originalSet)
答案 1 :(得分:8)
通过for循环创建新Set的过程比Set构造函数要快。尽管程度较小,但Maps也是这样。
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot querySnapshot = task.getResult();
if (querySnapshot.isEmpty()) {
// put code here to deal with no documents in the result
}
else {
// put code here to deal with documents present in the result
for (QueryDocumentSnapshot document : querySnapshot) {
}
}
}
}
答案 2 :(得分:5)
浅克隆:
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])
答案 3 :(得分:-1)
我需要复制(“克隆”)一个 JavaScript 集,这个问题激起了我对克隆副本完整性的兴趣,以及这些副本来源的扰动。
测试
var fruit = new Set(['apples', 'bananas']);
var provinces = new Set(['british columbia', 'nova scotia']);
console.log('fruit:', fruit)
console.log('provinces:', provinces)
// fruit: Set [ "apples", "bananas" ]
// provinces: Set [ "british columbia", "nova scotia" ]
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#implementing_basic_set_operations
function unionSets(setA, setB) {
let _union = new Set(setA);
for (let elem of setB) {
_union.add(elem)
}
return _union;
}
myUnionSet = unionSets(fruit, provinces);
console.log('myUnionSet:', myUnionSet)
// myUnionSet: Set(4) [ "apples", "bananas", "british columbia", "nova scotia" ]
// Tests:
fruit.delete('apples');
provinces.delete('british columbia');
console.log('fruit:', fruit)
console.log('provinces:', provinces)
console.log('myUnionSet:', myUnionSet)
// fruit: Set [ "bananas" ]
// provinces: Set [ "nova scotia" ]
// myUnionSet: Set(4) [ "apples", "bananas", "british columbia", "nova scotia" ]
答案 4 :(得分:-1)
如果 Map 包含非嵌套结构(例如 Map of Arrays),这里有一个快速的方法来深度复制它,对于任何感兴趣的人:
const newMap = new Map();
old.forEach((val, key) => newMap.set(key, [...old.get(key)]));