单层深拷贝 :
1、slice()方法
var arr = [1, 2, 3]
var newArr = arr.slice()
arr.push(4)
console.log(arr) //[ 1, 2, 3, 4 ]
console.log(newArr) //[ 1, 2, 3]
2、concat()方法
var arr = [1, 2, 3]
var newArr = arr.concat()
arr.push(4)
console.log(arr) //[ 1, 2, 3, 4 ]
console.log(newArr) //[ 1, 2, 3 ]
3、解构
//数组
var arr = [1, 2, 3]
var newArr = [...arr]
arr.push(4)
console.log(arr) //[ 1, 2, 3, 4 ]
console.log(newArr) //[ 1, 2, 3 ]
//对象
var obj = { name: 'winner' }
var newObj = { ...obj }
obj.name = 'dddd'
console.log(obj) //{ name: 'dddd' }
console.log(newObj) //{ name: 'winner' }
4、assign()
var obj = { name: 'winner' }
var newObj = Object.assign({}, obj)
obj.age = 20
console.log(obj) //{ name: 'winner', age: 20 }
console.log(newObj) //{ name: 'winner' }
5、filter
var arr = [1, 2]
var newArr = arr.filter((item) => {
return true
})
arr.push(88)
console.log(arr) //[ 1, 2, 88 ]
console.log(newArr) //[ 1, 2]
6、map
var arr = [1, 2]
var newArr = arr.map((item) => {
return item
})
arr.push(88)
console.log(arr) //[ 1, 2, 88 ]
console.log(newArr) //[ 1, 2 ]
多层深拷贝
1、遍历
function deepClone(obj) {
let objClone = Array.isArray(obj) ? [] : {}
if (obj && typeof obj === 'object') {
for (let key in obj) {
if (obj[key] && typeof obj[key] === 'object') {
objClone[key] = deepClone(obj[key])
} else {
objClone[key] = obj[key]
}
}
}
return objClone
}
2、JSON.parse(JSON.stringify())。对于undefined
、任意的函数以及 symbol
作为数组元素值时,JSON.stringify()
会将它们序列化为 null
//对象
var obj = {
a: 1,
b: { bb: 2 },
c: [1, 2, 3]
}
var copyObj = JSON.parse(JSON.stringify(obj))//这里实现了对obj的深拷贝
console.log(copyObj)
obj.b.bb = 10
console.log(copyObj)
//数组
var arr = [1, 2, [6], 7, [8, 9, [10]]]
var copyArr = JSON.parse(JSON.stringify(arr))//这里实现了对arr的深拷贝
console.log(copyArr)
arr[2] = 88
console.log(copyArr)