5 native clone JS package shades

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]";
        .toString.call isObject = {} var (value) === "[Object Object]"; 
        IF (the isArray || isObject) { 
          IF (the isArray) { 
            var clone = []; 
          } 
          IF (isObject) { 
            var clone = } {; 
          } 
          the console.log ( "I deep clones, the following recursive, here again pass"); 
          target [Key] = deepOrShallowClone (to true, clone, value); 
        } {the else 
          target [Key] = value; 
        } 
      } 
    } the else IF (arguments0 === to false) { 
      target = arguments [. 1]; 
    } {the 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);

  

Guess you like

Origin www.cnblogs.com/gushixianqiancheng/p/10963926.html