js深拷贝和浅拷贝
2020-06-16 本文已影响0人
海豚先生的博客
浅拷贝
Object.assign(target, source1, source2)
深拷贝
1 deepcopy
function deepCopy(obj, newObj) {
newObj = newObj || {};
for (var key in obj) {
if (typeof obj[key] === "object") {
newObj[key] = Array.isArray(obj[key]) ? [] : {};
deepCopy(obj[key], c[key]);
} else {
newObj[key] = obj[key];
}
}
return newObj;
}
2 jQuery的$.extend()
3 JSON.parse(JSON.stringify(obj));
4 lodash_.cloneDeep()
5 clone = structuredClone(original)
- 对数组的深拷贝
let box = list.slice();
let box = [].concat(list);
let box = [...list];
let box = Array.from(list);