一、JS深拷贝JSON.parse(JSON.string())的缺点不能拷贝函数,Date、正则表达式等,为解决这个问题,纯代码实现深拷贝功能,记录一下。
调用代码:
let time = new Date()
const sym = Symbol("symbol")
let obj = {
a:1,
b:2,
c:{a:1, b:2},
d: time,
e: /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/,
[sym]:"22222",
way:function(){
return a+b
}
}
let obj2 = deepCopy(obj)
结果展示

深拷贝实现代码如下:
function deepCopy(source , keepMap = new Map){
//判断是否为对象,不是直接返回数据
if( typeof source !== "object" || source == null){
return source
}
// 避免循环引用
if(keepMap.has(source)){
return keepMap.get(source);
}
let type;
if(Array.isArray(source)){
type = []
}else if(source instanceof Date){
type = new Date(source)
}else if(source instanceof RegExp){ //
type = new RegExp(source.source, source.flags)
}else{
type = {}
}
keepMap.set(source, type)
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if(typeof source[key] === "object" && source[key] !== null){
type[key] = deepCopy(source[key], keepMap)
}else{
type[key] = source[key]
}
}
}
//获取所有的Symbol属性
const symbols = Object.getOwnPropertySymbols(source)
for (const symkey of symbols) {
const element = source[symkey];
type[symkey] = deepCopy(element, keepMap)
}
return type
}