今天因为项目需要写了个Json格式的深拷贝(深度复制)。很简单,没有做其他的判断,代码如下:
function deepCopy(json){
if(typeof json == 'number' || typeof json == 'string' || typeof json == 'boolean'){
return json;
}else if(typeof json == 'object'){
if(json instanceof Array){
var newArr = [], i, len = json.length;
for(i = 0; i < len; i++){
newArr[i] = arguments.callee(json[i]);
}
return newArr;
}else{
var newObj = {};
for(var name in json){
newObj[name] = arguments.callee(json[name]);
}
return newObj;
}
}
}
刚才还犯了个错误,在使用concat连接数组的时候,还以为concat返回了一个新的数组,其实没有。concat方法不能用来做深拷贝。