使用递归函数实现深拷贝
const obj = {name: 'zzz',age: 18,hobby: ['篮球', '足球'],family: {baby: 'baby'}}
// 深拷贝 数组 对象 一定要先筛数组再筛对象,因为万物皆对象function deepcopy(newObj, oldObj) {for (const k in oldObj) {// 判断值是否属于array类if (oldObj[k] instanceof Array) {// 先将newo中hobby置空 newObj[hobby]=[]newObj[k] = []// 然后再将旧数据的数组值拷贝给新的数组值 newObj[hobby]=oldObj[hobby]deepcopy(newObj[k], oldObj[k])} else if (oldObj[k] instanceof Object) {newObj[k] = {}deepcopy(newObj[k], oldObj[k])} else {//newObj[k] ===newObj.name 给对象添加新属性newObj[k] = oldObj[k]}}}const newo = {}deepcopy(newo, obj)console.log(newo);newo.age = 11newo.hobby[0] = '羽毛球'newo.family.baby = 'bbbb'console.log(obj);
使用lodash的_.cloneDeep
方法实现深拷贝
官网下载lodash https://www.lodashjs.com/
//引用<script src="./lodash.min.js"></script>// lodash库const obj_l = {name: 'zzz',age: 18,hobby: ['篮球', '足球'],family: {baby: 'baby'}}const o_l = _.cloneDeep(obj_l)o_l.age = 11o_l.hobby[0] = '羽毛球'o_l.family.baby = 'bbbb'console.log(o_l);console.log(obj_l);
使用json的JSON.parse()JSON.stringify()
方法实现深拷贝
// json深拷贝const obj_j = {name: 'zzz',age: 18,hobby: ['篮球', '足球'],family: {baby: 'baby'}}// /JSON.stringify 将对象转为json字符串const o_j = JSON.parse(JSON.stringify(obj_j))o_j.age = 11o_j.hobby[0] = '羽毛球'o_j.family.baby = 'bbbb'console.log(o_j);console.log(obj_j);