function deepClone (o) {
if(typeof o !== 'object') return o
let n
if(Array.isArray(o)){
n = new Array(o.length)
o.forEach((v,i)=>{n[i] = deepClone(v)})
} else {
n = {}
Object.keys(o).forEach((key)=>{n[key] = deepClone(o[key])})
}
return n
}
测试
const a = {
a: [
1,
[4],
{
a: {
c: [4]
}
}
]
}
const b = deepClone(a);
a.c = "c";
console.log(a);
console.log(b);
console.log(a.c);
console.log(b.c);
网友评论