js数组和对象的深浅拷贝
数组和对象属于引用型数据类型。直接赋值实际上就是给了访问地址
let a = [1,2,3]; let b = a; b[0] = 0; console.log(a); //[0,2,3] console.log(b); //[0,2,3]
//对象同理
以上直接赋值方式为浅拷贝,在实际应用中,需要清楚需要哪种拷贝(多为深拷贝)。
数组和对象的深拷贝都可以用循环做到,但是不推荐。以下是比较好的方法:
//数组 let a = [1,2,3]; let b = [...a]; b[0] = 0; console.log(a) //[1,2,3] console.log(b) //[0,2,3] //对象 //方法一,json字符串,缺点,不好处理函数 let obj = {name:"张三"}; let obj1=JSON.parse(JSON.stringify(obj)); obj1.name = "李四"; console.log(obj);//{name:"张三"}; console.log(obj1);//{name:"李四"}; //方案二:递归解析法 function copyObject(obj){ let newObj = obj.constructor === Array?[]:{}; for(var i in obj){ if(typeof obj[i] === 'object'){ newObj[i] = arguments.callee(obj[i]); } else{ newObj[i]=obj[i]; } } return newObj; } function copyAll(type){ let obj2; if(typeof type === 'object'){ obj2 = copyObject(type); }else{ obj2 = type; } return obj2; }