深度克隆
程序员文章站
2022-03-07 08:59:11
封装一个函数用来克隆对象: ......
原始对象如下:
1 let obj = { 2 name: 'tw', 3 age: 12, 4 fit: ['12', '45', 78], 5 git: { 6 name: 'github', 7 www: 'http:.', 8 hub: { 9 name: "yu" 10 } 11 } 12 }
封装一个函数用来克隆对象:
1 function deepclone(origin, target) { 2 let tostr = object.prototype.tostring, 3 arrstr = '[object array]'; 4 for (let prop in origin) { 5 if (origin.hasownproperty(prop)) { 6 if (typeof (origin[prop]) == 'object') { 7 if (tostr.call(origin[prop]) == arrstr) { 8 target[prop] = []; 9 } else { 10 target[prop] = {}; 11 } 12 deepclone(origin[prop], target[prop]) 13 } else { 14 target[prop] = origin[prop]; 15 } 16 } 17 } 18 }