在写纯函数的时候,经常会把实参重新赋值给另外一个常量,目的是不产生副作用(即改变函数实参,不影响函数外面作用域的常量)。通常的做法是扩展运算符和Object.assign()
,但是这两个做法都算是浅拷贝。
也就是说,实参对象的第一层是基本类型的话,没有所谓的深浅拷贝,但要还是对象,就还是浅拷贝。
所以还是要写一个深拷贝函数:
function deepCopy(source) {
if (source === null || typeof source !== 'object') {
return source
}
const target = source instanceof Array ? [] : {}
for (const key in source) {
if (source.hasOwnProperty(key)) {
if (typeof source[key] === 'object') {
target[key] = deepCopy(source[key])
} else {
target[key] = source[key]
}
}
}
return target
}