(拷贝不是复制,拷贝后是新的堆内存)
一、数组深浅拷贝
let arr = [1,2,[3,4]]
1、数组浅拷贝:只是拷贝最外的一层,对象级别数据只拷贝引用;
- 数组方法:
slice
let newA = arr.slice(0);
console.log(arr[2]===newA[2]);/=true
- 数组方法:
concat
let arr1=[]
let newA = arr1.concat(arr);
console.log(arr[2]===newA[2]);/=true
- 数组方法:
map
let newA = arr.map((item)=>{
return item
});
console.log(arr[2]===newA[2]);/=true
- for in 循环
let newA = []
for(let key in arr){
newA[key] = arr[key]
}
console.log(arr[2]===newA[2]);/=true
- es6 方法
Object.assign
let newA = Object.assign([],arr)
console.log(arr[2]===newA[2]);/=true
- es6方法 解构
let newA = [...arr]
console.log(arr[2]===newA[2]);/=true
2、数组深拷贝:每一层的数据都会拷贝;
- JSON方法
let newA = JSON.parse(JSON.stringify(arr));
console.log(arr[2]===newA[2]);/=false
- 递归
let arr = [1,2,[3,4]];
let o = [];
function deepCopy(newObj, oldObj) {
for (let k in oldObj) {
let item = oldObj[k];
if (item instanceof Array) {
newObj[k] = [];
deepCopy(newObj[k], item);
}
else if (item instanceof Object) {
newObj[k] = {};
deepCopy(newObj[k], item);
}
else {
newObj[k] = item;
}
}
}
deepCopy(o, arr)
console.log(arr[2]===newA[2]);/=false
二、普通对象的深浅拷贝
let obj = { name:'zs',age:12 ,other:{ gender:'男' }}
对象的浅拷贝:只是拷贝一层,更深层次对象级别的只拷贝引用;
- for in循环
let newObj = {}
for(var k in obj){
newObj[k] = obj[k];
}
console.log(obj.other === newObj.other);/=true
- es6 方法
Object.assign
let newObj = Object.assign({},obj);
console.log(obj.other === newObj.other);/=true
let newObj = {...obj};
console.log(obj.other === newObj.other);/=true
对象的深拷贝:每一层的数据都会拷贝;
- JSON方法
- 弊端:会过滤掉属性值为
函数、Symbol、undefined
的属性; 正则对象
深拷贝后为空值;日期对象
深拷贝后为字符串;
- 弊端:会过滤掉属性值为
let newObj = JSON.parse(JSON.stringify(obj));
console.log(obj.other === newObj.other);/=false
- 递归
let o = {};
function deepCopy(newObj, oldObj) {
for (let k in oldObj) {
let item = oldObj[k];
if (item instanceof Array) {
newObj[k] = [];
deepCopy(newObj[k], item);
}
else if (item instanceof Object) {
newObj[k] = {};
deepCopy(newObj[k], item);
}
else {
newObj[k] = item;
}
}
}
deepCopy(o, obj)
console.log(o);/= { name: 'zs', age: 12, other: { gender: '男' } }
console.log(o.other==obj.other);/=false
- 递归2
let obj = {
a:100,
b:[10,20,30],
c:{x:100},
d:/\d+/g,
e:function(){console.log('aa');},
f:null,
g:undefined,
h:Symbol(1),
i:new Date()
}
// let obj2 = JSON.parse(JSON.stringify(obj))
function deepClone(obj){
if(obj === null){return null};
if(typeof(obj) !== 'object'){return obj};
if(obj instanceof RegExp){ return new RegExp(obj)};
if(obj instanceof Date){ return new Date(obj)};
// 保证克隆内容与之前都属于一个类
let newObj = new obj.constructor;
for(let key in obj){
if(obj.hasOwnProperty(key)){ //过滤原型
newObj[key] = deepClone(obj[key])
}
}
return newObj;
}
let obj2 = deepClone(obj);
console.log(obj2);
console.log(obj2.e === obj.e);/= true,函数对象是一样的,不过不影响,
/obj无法修改函数内部,对obj2不产生影响,只是两个不同的对象属性指向了同一个(不能修改的)函数对象