深拷贝的实现
(后续完善)最近面试经常会被问到关于深拷贝和浅拷贝的问题, 所以总结了一下:
一. 递归
const arr = [1, 2, [3, 4, 5, [6, 7, 8]]]
const obj = {
name: 'zhangsan',
age: 18,
fav: null,
sayName: function() {
return this.name
},
like: {
a: 'yes',
b: 'no'
},
bool: true
}
function deepClone(target) {
// 拦截基本数据类型, null, undefined Date和正则 ,抛出错误并原样返回
if (
typeof target !== 'object' ||
target == null ||
target == undefined ||
target instanceof Date ||
target instanceof RegExp
) {
// 不可以使用throw 会导致后面代码无法执行, 后续补充throw知识
// throw new Error('不符合规范,请检查入参是否为数组或对象')
return target // 原样返回
}
// 判断入参的数据类型 数组/对象
const newTarget = Array.isArray(target) ? [] : {}
/**
* Object.keys(target) 查阅MDN
* 此方法会对object的属性进行一次排序 排序的方法不明(像是Unicode或是ASCII,后续确认)
* 对于数组则直接返回其下标
*/
Object.keys(target).forEach(
key => (newTarget[key] = target[key] instanceof Object ? deepClone(target[key]) : target[key])
)
return newTarget
}
const newArr = deepClone(obj)
console.log(newArr);
二.
JSON.stringify()
但缺点是不能识别function, undefined symbol BigInt等, 会转换成null或者报错
三. 第三方库 lodash的cloneDeep() 后面看看源码

浙公网安备 33010602011771号