Deep copy (perfect copy):
① If it is a basic data type, return directly;
② If it is a RegExp or Data type, return the corresponding type;
③ If it is a complex data type, recurse;
④ Consider the issue of circular references.
function deepClone(obj, hash = new WeakMap) {
if (obj instanceof RegExp) {
return new RegExp(obj)
}
if (obj instanceof Date) {
return new Date(obj)
}
if (obj == null || typeof obj !== 'object') {
return obj
}
if (hash.has(obj)) {
return hash.get(obj)
}
let a = new obj.constructor()
hash.set(obj, a)
for (let key in obj) {
//递归
if (obj.hasOwnProperty(key)) {
a[key] = deepClone(obj[key], hash)
}
}
return a
}
var show = {
name: '小明',
fn: function () {
console.log(1) },
age: null,
pic: undefined,
}
var show2 = deepClone(show)
show2.name = "Mary"
console.log(show, show2)
Shallow copy (only one layer can be copied): Object.assign and for in make {} and [] copies.
//Object.assign()拷贝方法
//拷贝{}
a = {
name:"张三"};
b = Object.assign({
},a);
b.name = "李四"; //拷贝完之后进行改变属性,测试拷贝的属性值改变原数据是否改变。
console.log(a,b);
//输出:{name:"张三"}
{
name:"李四"} (拷贝成功)
//拷贝[]
a = ["1","2","3"];
b = Object.assign([],a);
b[1]="hello";
console.log(a,b)
//输出:["1","2","3"]
["1","hello","3"] (拷贝成功)
//for in拷贝方法
var copy = function(a){
var res = a.constructor();
for(var key in a){
if(a.hasOwnProperty(key)){
res[key] = a[key]
}
}
return res;
}
a = {
name:"123",people:{
name:"456"}};
b = copy(a);
b.people.name="hello";
a = ["a","b","c"];b = copy(a);
b[1] = 0;//拷贝完之后进行改变属性,测试拷贝的属性值改变原数据是否改变。
console.log(a,b)
//输出:["a","b","c"]
["a","0","c"] (拷贝成功)