深度克隆

 原始对象如下:
 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     }

 

posted @ 2019-07-31 23:10  秋华啦啦  阅读(375)  评论(0编辑  收藏  举报