深拷贝 deepAssign

实现代码:

<script type="text/javascript">

    Object.deepAssign = function() {
      var args = Array.from(arguments);
      return args.reduce(deepClone,args[0]);

      function deepClone(target,obj){
          if(!target) target = Array.isArray(obj)?[]:{};
          if(obj && typeof obj==="object"){
              for(key in obj){
                  if(obj.hasOwnProperty(key)){
                      //判断ojb子元素是否为对象,如果是,递归复制
                      if(obj[key]&&typeof obj[key] ==="object"){
                          target[key] = deepClone(target[key],obj[key]);
                      }else{
                          //如果不是,简单复制
                          target[key] = obj[key];
                      }
                  }
              }
          }
          return target;
      }
    }
    // 测验代码
    var obj1 = {a:1, b:2},
        obj2 = {
          a:4,
          rules: {
            code: 'sn0-101',
            text: '芯片'
          }
        },
        obj3 = {
          addrs: {
            bj: '北京',
            sh: '上海'
          }
        };

    Object.deepAssign(obj1,obj2,obj3);
    obj1.rules.name = '语言';

    console.log(obj1,obj2,obj3);
</script>

 

测验结果:

posted @ 2018-11-08 11:11  【云】风过无痕  阅读(729)  评论(0编辑  收藏  举报