时间:2022-04-01 09:45:08 | 栏目:JavaScript代码 | 点击:次
浅克隆无法copy数组和对象
var obj = { name : "abs", age : '18', sex : 'male' } var obj1 = {} function clone(Origin,target) { target = target || {};//防止用户不输入target for(var k in Origin){ target[k] = Origin[k]; } } clone(obj,obj1);
先判断它是什么,原始值,数组还是对象,分别处理
copy
var obj = { name : 'lin', age : '18', sex : 'male', card : [1,2,3,4], wife : { name : 'bcsds', son : { name : 'aaa' }, age : '23' } } var obj1 = {} //原始值和对象数组typeof返回值有区别 function deepClone(origin,target) { target = target || {}; for(var k in origin) { if(origin.hasOwnProperty(k)){ if(typeof(origin[k]) == 'object') { if(Object.prototype.toString.call(origin[k]) == '[object Array]') { target[k] = []; }else { target[k] = {}; } deepClone(origin[k],target[k]); }else { target[k] = origin[k]; } } } } deepClone(obj,obj1);