码迷,mamicode.com
首页 > Web开发 > 详细

5原生JS封装深浅克隆

时间:2019-06-02 19:20:43      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:type   string   sha   fun   null   iso   after   hal   one   

function deepOrShallowClone() {
    var target = null;
    var arguments0 = arguments[0];
    var lastArguments = arguments[arguments.length - 1];
    //首次执行arguments.length为2,后来递归执行arguments.length为3
    if (arguments0 === true) {
      if ({}.toString.call(lastArguments) === "[object Array]") {
      //{}.toString.call也可以用Object.prototype.toString.call代替
        target = [];
      }
      if ({}.toString.call(lastArguments) === "[object Object]") {
        target = {};
      }
      for (var key in lastArguments) {
        var value = lastArguments[key];
        var isArray = {}.toString.call(value) === "[object Array]";
        var isObject = {}.toString.call(value) === "[object Object]";
        if (isArray || isObject) {
          if (isArray) {
            var clone = [];
          }
          if (isObject) {
            var clone = {};
          }
          console.log("我是深克隆,将通过下面的递归,再次路过这里");
          target[key] = deepOrShallowClone(true, clone, value);
        } else {
          target[key] = value;
        }
      }
    } else if (arguments0 === false) {
      target = arguments[1];
    } else {
      target = arguments0;
    }
    return target;
  }
  var beforeClone = {a: 1, b: [2, {c: 3, d: {e: 4, f: [5, {g: 6}]}}]};
  var afterShallowClone1 = deepOrShallowClone(beforeClone);
  var afterShallowClone2 = deepOrShallowClone(false, beforeClone);
  var afterDeepClone = deepOrShallowClone(true, beforeClone);
  console.log(afterShallowClone1);
  console.log(afterShallowClone2);
  console.log(afterDeepClone);

  

5原生JS封装深浅克隆

标签:type   string   sha   fun   null   iso   after   hal   one   

原文地址:https://www.cnblogs.com/gushixianqiancheng/p/10963926.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!