增强版:
function clone(obj){
var buf ;
if(obj instanceof Array){
buf = [];
var i = obj.length;
while(i--){
buf[i] = clone(obj[i])
}
return buf;
}
else if(obj instanceof Object){
buf = {};
for(var k in obj){
buf[k] = clone(obj[k])
}
return buf;
}
else{
return obj
}
}
曾经版:
var obj1={
a:1,
b:true,
c:'你好',
d:{
e:5,
f:[1,2,3]
}
};
//方法一:
function deepcopy(obj){
var obj2={};
for(var key in obj){
if(typeof obj[key]==='object'){
obj2[key]=deepcopy(obj[key])
}else{
obj2[key]=obj[key]
}
}
return obj2;
}
//方法二:
var obj2 = JSON.parse( JSON.stringify(obj1) )
网友评论