几个深拷贝函数


2019-9-3 前端基础

深拷贝方法1

/**
 * 深拷贝函数
 * @param obj
 */
function deepCopy (obj) {
  let result = {}
  let keys = Object.keys(obj),
    key = null,
    temp = null;
  for (let i = 0, len = keys.length; i < len; i++) {
    key = keys[i];
    temp = obj[key];
    if (temp && typeof temp === 'object') {
      result[key] = deepCopy(temp);
    } else {
      result[key] = temp;
    }
  }
  return result;
}

var obj = {
  a: 1,
  b: null,
  c: undefined,
  symbol: Symbol('foo'),
  f: function (a, b) { return a + b; },
  s: "string"
}
var copy = deepCopy(obj)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

深拷贝方法2

/**
* 深拷贝函数
* @param1 parent
* @param2 copy
*/
function deepCopy(parent, copy) {
    copy = copy || {}
    for(var i in parent) {
        if(parent.hasOwnProperty(i)) {
            if(typeof parent[i]  === 'object') {
                copy[i] = Array.isArray(parent[i]) ? [] : {}
                deepCopy(parent[i], copy[i])
            }else {
                copy[i] = parent[i];
            }
        }
    }
    return copy;
}
var obj = {
    a:1,
    b:"str",
    c:Symbol("c"),
    d:function(x,y){
        return x+y;
    },
    e:undefined,
    f:null,
    g: [1,2,3]
}
 
var obj2 = deepCopy(obj);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

深拷贝方法3

function* deepCopy(obj) {
    let keys = Object.keys(obj);
    for(let i=0;i<keys.length;i++) {
        let key = keys[i];
        let val = obj[key];
        if(obj.hasOwnProperty(key)){
            if(typeof val === 'Object') {
                yield* deepCopy(val);
            }else {
                yield val;
            }
        }
    }
}

var obj = {
    a:1,
    b:null,
    c:undefined,
    symbol: Symbol('foo'),
    f: function(a, b) { return a+b;},
    s: "string"
}
let copy = {};
for(let [key,value] of deepCopy(obj)) {
   copy[key] = value;
}
console.log(copy);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Thomas: 10/11/2019, 3:14:55 PM