一、对象、数组通用
遍历赋值(深拷贝)
// 定义遍历赋值的函数
let cloneObj = function (obj) {
let newObj = obj instanceof Array ? [] : {}
for (let key in obj) {
let val = obj[key]
newObj[key] = typeof val === 'object' ? cloneObj(val) : val
}
return newObj
}
// 测试
const list = {
id: 'a',
title: 'A',
authors: ['y', 'h'],
}
let list2 = cloneObj(list)
list2.authors[0] = 'a'
console.log(list)
console.log(list2)
借助 JSON (深拷贝)
先将对象变为字符串,然后再变为 json 对象。
- undefined 和 function 类型的属性会被忽略,而 Date 类型的属性则会被转换为字符串
let newObj = JSON.parse(JSON.stringify(obj))
// 测试
const list = {
id: 'a',
title: 'A',
authors: ['y', 'h'],
}
let list2 = JSON.parse(JSON.stringify(list))
list2.authors[0] = 'a'
console.log(list)
console.log(list2)
// 结果与上面一致
二、特定用法
对象拷贝-扩展运算符(浅拷贝)
只能实现表层的拷贝,深层的不行
let newObj = { ...obj }
// 测试
const list = {
id: 'a',
title: 'A',
authors: ['y', 'h'],
}
let list2 = { ...list }
list2.authors[0] = 'a'
list2.id = 'c'
console.log(list)
console.log(list2)
数组拷贝-concat 方法(浅拷贝)
借助数组的方法 concat,只能实现表层拷贝
let newArr = [].concat(arr)
// 测试
const list = [
1,
2,
3,
{
id: 'a',
title: 'A',
},
]
let list2 = [].concat(list)
list2[0] = 'a'
list2[3].id = 'c'
console.log(list)
console.log(list2)
数组拷贝-扩展运算符(浅拷贝)
与对象的扩展运算符用法一致
let newArr = [...arr]
// 测试
const list = [
1,
2,
3,
{
id: 'a',
title: 'A',
},
]
let list2 = [].concat(list)
list2[0] = 'a'
list2[3].id = 'c'
console.log(list)
console.log(list2)
// 结果与上面一致