前端提高篇(二十六)练习7:对象的深度克隆
程序员文章站
2024-01-04 20:40:46
...
注意数组和对象的判断
var obj = {
a:1,
b:false,
c:{a:2, b:true, c:{a:3, b:false}},
d:[1,2,3,[1,2,3]],
}
function clone(obj){
//数组
if (obj instanceof Array){
var ary = [];
for (var i = 0; i < obj.length; i++){
ary[i] = clone(obj[i]);
}
return ary;
}
//对象
if (obj instanceof Object){
var newObj = {};
for (var j in obj){
newObj[j] = clone(obj[j]);
}
return newObj
}
return obj;//如果是简单值,就直接返回
}
var a = clone(obj);
运行结果:当obj改变时,a不变