只针对Object类型的深拷贝,自己总结的三种方式,分别为:递归的方式、广度优先遍历的方式、使用JSON.parse()方法。

  1. 递归:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function copy(source) {
    var key, target
    if (type(source) === "object") {
    target = {}
    for (key in source) {
    if (type(source[key]) === "array" || "object") {
    target[key] = copy(source[key])
    } else if (source[key] !== undefined) target[key] = source[key]
    }
    }
    return target
    }
  2. 广度优先遍历

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    function copy(data){
    var obj = {};
    var originQueue = [data];
    var copyQueue = [obj];
    while(originQueue.length > 0){
    var _data = originQueue.shift();
    var _obj = copyQueue.shift();
    for(var key in _data){
    var _value = _data[key]
    if(typeof _value !== 'object'){
    _obj[key] = _value;
    } else {
    originQueue.push(_value);
    _obj[key] = {};
    copyQueue.push(_obj[key]);
    }
    }
    }
    return obj;
    }
  3. JSON

    1
    JSON.parse(JSON.stringify(source))

参考: http://blog.csdn.net/sysuzhyupeng/article/details/70340598