js里的深度克隆

ES6

数组克隆

let arr = [1,2,3,4,5];
let arr1 = [...arr];
arr1 = ["a","b","c"];
arr;//[1,2,3,4,5]
arr1;//["a","b","c"]

对象克隆

let obj = {name:"tony",age:18};
let obj1 = {...obj};
obj1.age = 16;
obj;//{name:"tony",age:18}
obj1;//{name:"tony",age:16}

附ES5

仅供参考

数组的克隆

 function deepClone (event) {
  var arr = [],
    i = 0,
    len = event.length;
  for (; i < len; i++) {
    if (event[i] instanceof Array) {
      arr[i] = deepClone (event[i]);
    } else arr[i] = event[i];
  }
  return arr;
}

对象的克隆

function deepClone(obj){
    var newObj= obj instanceof Array?[]:{};
    for(var i in obj){
       newObj[i]=typeof obj[i]=='object'?  
       deepClone(obj[i]):obj[i];    
    }
    return newObj;
}

若有不妥之处请指正,
此外,可以使用lodash进行深度克隆的操作

posted @ 2019-03-14 09:31  沈瀚  阅读(514)  评论(1编辑  收藏  举报