Open ntscshen opened 6 years ago
...
Object.assign
[].concat()
arr.slice(0)
// 1. 扩展运算符
const arr = ['lin', 'is', 'handsome']
const newArr = [...arr]
// 2. Object.assign
const obj = {
name: 'lin'
}
const newObj = Object.assign({}, obj)
// 3. slice
const arr = ['lin', 'is', 'handsome']
const newArr = arr.slice(0)
// 4. concat
const arr = ['lin', 'is', 'handsome']
const newArr = [].concat(arr)
let obj = {
numberParams:1,
functionParams:() => {
console.log('昨天基金全是绿的,只有我的眼睛是红的');
},
objParams:{
a:1,
b:2
}
}
const copyObj = (obj = {}) => {
let newObj = {};
if (typeof obj == 'object' && obj !== null) {
newObj = Array.isArray(obj) ? [] : {}
for(let key in obj) {
newObj[key] = copyObj(obj[key])
}
} else {
newObj = obj
}
return newObj
}
const temp = copyObj(obj);
console.log(temp === obj)
temp.numberParams = 999;
obj.numberParams = 222;
console.log('obj: ', obj);
console.log('temp: ', temp)
JS的深浅拷贝
手动实现一个深度拷贝