实现深拷贝的方式
1、使用assign
常规的操作可以,但是追加对象中数组元素的时候,还是会受到影响
let obj = {
name:'hanhan',
age:18,
arr:[11,33,55]
}
let newObj = {};
Object.assign(newObj, obj);
//追加数组元素的时候,会影响原对象
obj.arr.push(88)
let objUser = {
name: '小明',
age: 18,
sex: '男',
arr: [11, 22, 33]
}
let newObjUser = {};
Object.assign(newObjUser, objUser)
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(3)}
objUser.arr.push(88);
console.log(objUser);//{name: '小明', age: 18, sex: '男', arr: Array(4)}
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(4)}
0bject.assign(newObj,obj):将原对象的属性和方法复制到新的目标中,第一个参数是接收,第二个参数是赋值
2、使用JSON进行深拷贝,如果对象中存在方法,方法是拷贝不过去的
let objUser = {
name: '小明',
age: 18,
sex: '男',
arr: [11, 22, 33],
fun() {
console.log('今天是阴天,天气并不是很好');
}
}
let newObjUser = JSON.parse(JSON.stringify(objUser));
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(3)}
objUser.arr.push(88);
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(3)}
3、剩余参数拷贝
let objUser = {
name: '小明',
age: 18,
sex: '男',
arr: [11, 22, 33],
fun() {
console.log('今天是阴天,天气并不是很好');
}
}
let newObjUser = {...objUser};
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(3), fun: ƒ}
objUser.arr.push(88);
objUser.address = '青岛大学';
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(4), fun: ƒ}
4、定义深拷贝
(1)实现深度拷贝的方式一
function deepClone(obj){
let objClone = Array.isArray(obj)?[]:{}; //新建一个空数组或者空对象
// 判断是否为引用类型数据
if(obj && typeof obj==="object"){
for(key in obj){
if(obj.hasOwnProperty(key)){
//判断ojb子元素是否为对象,如果是,递归复制
if(obj[key]&&typeof obj[key] ==="object"){
objClone[key] = deepClone(obj[key]);
}else{
//如果不是,简单复制
objClone[key] = obj[key];
}
}
}
}
return objClone;
}
let a=[1,2,3,4],
let b= deepClone(a);
a[0]=2;
console.log(a,b);
// 在这里还有一个问题,
let arrNumber = [1,2,3]
for(let key in arrNumber){
console.log(key);//key值为索引值0,1,2
}
(2)实现深度拷贝方式二
function deepClone(target) {
let newClone;
if(Object.prototype.toString.call(target) === '[object Array]'){
newClone = [];
}else if(Object.prototype.toString.call(target) === '[object Object]'){
newClone = {}
}else {
return
}
for(let key in target) {
if(target[key] && typeof target[key] === 'object'){
newClone[key] = deepClone(target[key])
}else {
newClone[key] = target[key]
}
}
return newClone
}
let objUser = {
name: '小明',
age: 18,
sex: '男',
arr: [11, 22, 33],
fun() {
console.log('今天是阴天,天气并不是很好');
}
}
let newObjUser = deepClone(objUser);
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(3), fun: ƒ}
objUser.arr.push(88);
console.log(newObjUser);//{name: '小明', age: 18, sex: '男', arr: Array(3), fun: ƒ}
let arr = ['苹果', '西瓜', '香蕉'];
let newArr = deepClone(arr);
console.log(newArr);//(3) ['苹果', '西瓜', '香蕉']
arr.push('草莓');
console.log(newArr);//(3) ['苹果', '西瓜', '香蕉']