1、数组浅拷贝
var arr = [1, 2, [3, 4] ];
第一种:var arr1 = arr.slice(0)
第二种:var arr2 = arr.concat()
arr[2][0] = 8;
arr[0]= 9;
console.log(arr) // [9, 2, [8, 4] ]
console.log(arr1) // [1, 2, [8, 4] ]
console.log(arr2) // [1, 2, [8, 4] ]
2、对象浅拷贝
(1)new Object( )
var obj = {name: ‘abc‘, age: 18, arr: [1,2], o: {id: 99}}
var obj2 = new Object()
obj2.name = obj.name
obj2.age = obj.age
obj2.o = obj.o
obj2.age = 20;
obj2.o.id = 88
console.log(obj) // {name: ‘abc‘, age: 18, arr: [1,2], o: {id: 88}}
console.log(obj2) // {name: ‘abc‘, age: 20, arr: [1,2], o: {id: 88}}
(2)Object.assign(obj1,obj2)
var obj1 = {a: 1, b: 2}
var obj2 = {x: 1, y: 2, id: {o: 99}}
Object.assign(obj1,obj2)
obj2.id.o = 77
obj2.x = 8
console.log(obj1) // { a: 1, b: 2, x: 1, y: 2, id: {o: 77}}
console.log(obj2) // {x: 8, y: 2, id: {o: 77}}
3、对象深拷贝
(1)JSON.parse(JSON.stringify(obj))(对象中的function函数无法拷贝)
var obj = {name: ‘abc‘, age: 18, arr: [1, 2], o: {id: 99}, fun: function(){console.log(1)}}
var obj2 = JSON.parse(JSON.stringify(obj))
obj.o.id = 100
console.log(obj) //{name: ‘abc‘, age: 18, arr: [1, 2],o: {id: 100}, fun:function(){console.log(1)}}
console.log(obj2) //{name: ‘abc‘, age: 18, arr: [1, 2],o: {id: 99}}
(2)公共方法(可以拷贝对象中的function函数)
function deep(obj1,obj2){
for(var key in obj2){
if(typeof obj2[key] == ‘object‘){
obj1[key] = obj2[key].constructor === Array ? [] : {}
deep(obj1[key], obj2[key])
}else{
obj1[key] = obj2[key]
}
}
return obj1
}
4、扩展运算符浅拷贝
var a1 = [1,{id:2},3]
var a2 = [...a1]
a2[1].id = 5
console.log(a1) // [1,{id:5},3]