zoukankan      html  css  js  c++  java
  • js优雅的实现深拷贝的方法

    1、通过 JSON 对象实现深拷贝

    //通过js的内置对象JSON来进行数组对象的深拷贝
    function deepClone2(obj) {
      var _obj = JSON.stringify(obj),
        objClone = JSON.parse(_obj);
      return objClone;
    }

    JSON对象实现深拷贝的一些问题
    * 无法实现对对象中方法的深拷贝

    2、通过jQuery的extend方法实现深拷贝

    var array = [1,2,3,4];
    var newArray = $.extend(true,[],array);

    3、使用递归的方式实现深拷贝

    //使用递归的方式实现数组、对象的深拷贝
    function deepClone1(obj) {
      //判断拷贝的要进行深拷贝的是数组还是对象,是数组的话进行数组拷贝,对象的话进行对象拷贝
      var objClone = Array.isArray(obj) ? [] : {};
      //进行深拷贝的不能为空,并且是对象或者是
      if (obj && typeof obj === "object") {
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] && typeof obj[key] === "object") {
              objClone[key] = deepClone1(obj[key]);
            } else {
              objClone[key] = obj[key];
            }
          }
        }
      }
      return objClone;
    }

    4、Object.assign()拷贝

    当对象中只有一级属性,没有二级属性的时候,此方法为深拷贝,但是对象中有对象的时候,此方法,在二级属性以后就是浅拷贝。

    5、扩展运算符对单层实现深拷贝

    当对象中只有一级属性,没有二级属性的时候,此方法为深拷贝,但是对象中有对象的时候,此方法,在二级属性以后就是浅拷贝。

    6、lodash函数库实现深拷贝

    lodash很热门的函数库,提供了 lodash.cloneDeep()实现深拷贝

    原文参考:

    https://blog.csdn.net/chentony123/article/details/81428803

  • 相关阅读:
    Unity The Method Signature Matching Rule
    Unity The Property Matching Rule
    Unity The Type Matching Rule
    Unity The Custom Attribute Matching Rule
    Unity The Member Name Matching Rule
    Unity No Policies
    Unity The Return Type Matching Rule
    Unity The Parameter Type Matching Rule
    Unity The Namespace Matching Rule
    关于TSQL递归查询的(转)
  • 原文地址:https://www.cnblogs.com/art-poet/p/12201742.html
Copyright © 2011-2022 走看看