封裝一個函數用來克隆對象: ...
原始對象如下:
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 }