引自://blog.csdn.net/FungLeo/article/details/54931379

在js中,数组和对象的复制如果使用=号来进行复制,那只是浅拷贝。

下面是数组和对象的深拷贝

数组的深拷贝

1.for 循环实现数组的深拷贝

var arr = [1,2,3,4,5]
var arr2 = copyArr(arr)
function copyArr(arr) {
    let res = []
    for (let i = 0; i < arr.length; i++) {
     res.push(arr[i])
    }
    return res
}

2.slice 方法实现数组的深拷贝

他是将原数组中抽离部分出来形成一个新数组

var arr = [1,2,3,4,5]
var arr2 = arr.slice(0)
arr[2] = 5
console.log(arr)
console.log(arr2)

3.concat 方法实现数组的深拷贝

var arr = [1,2,3,4,5]
var arr2 = arr.concat()
arr[2] = 5
console.log(arr)
console.log(arr2)

4.ES6扩展运算符实现数组的深拷贝

var arr = [1,2,3,4,5]
var [ ...arr2 ] = arr
arr[2] = 5
console.log(arr)
console.log(arr2)

对象的深拷贝

1.for循环

作者:六师兄Leon
链接:https://www.zhihu.com/question/23031215/answer/124017500
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

var china = {
          nation : '中国',
          birthplaces:['北京','上海','广州'],
          skincolr :'yellow',
          friends:['sk','ls']
      }
      //深复制,要想达到深复制就需要用递归
      function deepCopy(o,c){
        var c = c || {}
        for(var i in o){
        if(typeof o[i] === 'object'){
                          //要考虑深复制问题了
                      if(o[i].constructor === Array){
                        //这是数组
                        c[i] =[]
                    }else{
                        //这是对象
                        c[i] = {}
                    }
                    deepCopy(o[i],c[i])
                    }else{
                         c[i] = o[i]
                    }
             }
             return c
      }
      var result = {name:'result'}
      result = deepCopy(china,result)
      console.dir(result)

2:通过JSON解析解决

var result = JSON.parse(JSON.stringify(test))

不过这有局限性:

  • 无法复制函数
  • 原型链没了,对象就是object,所属的类没了

3.jquery

jQuery.extend(true, { a : { a : "a" } }, { a : { b : "b" } } );

 

作者:知乎用户
链接:https://www.zhihu.com/question/23031215/answer/31950463
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

jQuery.extend = jQuery.fn.extend = function() {
    var src, copyIsArray, copy, name, options, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;

        // skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }

    for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};

 

posted on 2018-03-13 20:19  坚持不懈❥  阅读(3069)  评论(0编辑  收藏  举报