Appearance
深拷贝
本节目标:理解“深拷贝”的核心思路,并能把它用于实际开发或面试表达。 特点:
- 只复制基本数据类型的值;
- 复制出来的对象属性变化不会影响原对象。
主要有两种方法: 一、JSON.stringify/parse const originArray = [1, 2, 3, 4, 5]; const cloneArray = JSON.parse(JSON.stringify(originArray)); console.log(cloneArray === originArray); // false
const originObj = { a: 'a', b: 'b', c: [1, 2, 3], d: { dd: 'dd' } };
const cloneObj = JSON.parse(JSON.stringify(originObj));
console.log(cloneObj === originObj); // falsecloneObj.a = 'aa';
cloneObj.c = [1, 1, 1];
cloneObj.d.dd = 'doubled';console.log(cloneObj); // {a:'aa',b:'b',c:[1,1,1],d:{dd:'doubled'}};
console.log(originObj); // {a:'a',b:'b',c:[1,2,3],d:{dd:'dd'}};**此方法局限**- 如果要复制的值是
undefined、function、symbol,会在转换过程中被忽略
const originObj = {
name: 'axuebin',
sayHello: function () {
console.log('Hello World');
}
}
console.log(originObj); // {name: "axuebin", sayHello: ƒ}
const cloneObj = JSON.parse(JSON.stringify(originObj));
console.log(cloneObj); // {name: "axuebin"}**二、深拷贝(使用递归)**
function deepCopy(p, c) {
c = c || {};
for (var i in p) {
if (p.hasOwnProperty(i)) {
if (typeof p[i] === 'object') {
c[i] = Array.isArray(p[i]) ? [] : {};
deepCopy(p[i], c[i]);
}
} else {
c[i] = p[i];
}
}
}Object.prototype.clone = function () { //
对象的深拷贝获取对应的构造函数 `[]` 或者{} var newObject = this.constructor === Array ? [] : {}
;
`//`遍历对象的属性in this[e] for (let e in this) { //
对象中的属性如果还是对象 那就继续递归 否则就返回基本的数据类型newObject[e] = typeof this[e] === 'object' ? this[e].clone() : this[e] } return newObject }
