JS深拷贝的方法
-
JSON.parse(JSON.stringify(a))
简单深拷贝的方法
缺点:- 不支持undefined、Date、正则、函数
- 不支持引用
例:
var b = { a:2, b:'b' } var a = { a:1, b:b } var c = JSON.parse(JSON.stringify(a))
上面的例子中a.b引用了b,这样就不能用JSON.parer()这种方法进行深拷贝
递归
要点:
- 判断类型
- 不拷贝原型上的属性方法
- 处理环(循环引用)
const deepclone = (a, cache) => {
if (!cache) {
cache = new Map();
}
// a是对象
if (a instanceof Object) {
//处理循环引用的情况
if (cache.get(a)) {
return cache.get(a);
}
let result;
//a是函数
if (a instanceof Function) {
//a是普通函数
if (a.prototype) {
result = function () {
return a.apply(this, arguments);
};
} else {
// 箭头函数
result = (...args) => {
a.call(undefined, ...args);
};
}
}
//a是Date
else if (a instanceof Date) {
result = new Date(a - 0); //a-0 可以将Date转为对应的时间戳
}
//a是Regexp
else if (a instanceof RegExp) {
result = new RegExp(a.source, a.flags);
}
//a是普通对象
else {
result = {};
}
cache.set(a, result);
//拷贝其他属性
for (var key in a) {
//只拷贝自身属性,原型上的属性不拷贝
if (a.hasOwnProperty(key)) {
result[key] = deepclone(a[key], cache);
}
}
return result;
} else {
//a是原始类型 string number boole null undefined Symbol bigint
return a;
}
};
const a = {
number: 1,
bool: false,
str: "hi",
empty1: undefined,
empty2: null,
array: [
{ name: "aa", age: 18 },
{ name: "bb", age: 19 },
],
date: new Date(2000, 0, 1, 20, 30, 0),
regex: /\.(j|t)sx/i,
obj: { name: "aaa", age: 18 },
f1: (a, b) => a + b,
f2: function (a, b) {
return a + b;
},
};
a.self = a;
const b = deepclone(a);
console.log(b.self === b); // true
b.self = "hi";
console.log(a.self !== "hi"); //true