【工具函数】深拷贝
<h4>深拷贝</h4>
<hr />
<p>深拷贝是在堆内存中新开了一个内存空间
解题思路:</p>
<ul>
<li>基本数据类型</li>
<li>数组</li>
<li>不是数组(Object)</li>
</ul>
<pre><code>const a = {
a: [
1,
[4],
{
a: {
c: [4]
}
}
]
}
function deepCopy(o){
if(typeof(o) !== 'object') return o;
let n ;
if(Array.isArray(o)){
n = new Array(o.length);
o.forEach((v,i) =>{
n[i] = deepCopy(v)
})
}
else if(!Array.isArray(o)){
n = {};
Object.keys(o).forEach(key =>{
n[key] = deepCopy(o[key])
})
}
return n;
}
const b = deepCopy(a);
a.c = "c";
console.log(a);
console.log(b);
console.log(a.c);
console.log(b.c);
</code></pre>
<p>引用记录:
<a href="https://lucifer.ren/fe-interview/#/./topics/algorthimn/deepCopy">https://lucifer.ren/fe-interview/#/./topics/algorthimn/deepCopy</a></p>