function copy(source,destination) { var sourceCopy = source instanceof Array ? [] : {}; for (var item in source) { sourceCopy[item] = typeof source[item] === 'object' && destination ? copy(source[item]) : source[item]; } return sourceCopy; };
//调用 var obj = {id:1,name:'Tom',children:{id:2,name:'Jack'}}; var arr = [ {id:1,name:'Tom'}, {id:2,name:'Marry'}, {id:3,name:'Jack'}, ]; var obj2 = copy(obj); obj2.name = 'Daisy'; var obj3 = copy(obj,true); obj3.children.name = 'Daisy'; var arr2 = copy(arr,true); arr2[0].name = 'Daisy'; alert(obj.name);//Tom alert(obj.children.name);//Jack alert(arr[0].name);//Tom