深拷贝
1、简单深拷贝
除了基本数据类型(null、string、boolean、undefined、number、symbol),引用数据类型中 如果对象中不存在时间类型和正则表达式等类型对象,则可用简单的JSON序列化进行转化。 例如:
var copyObj = JSON.parse(JSON.stringify(obj))
2、存在Date和正则表达式的深拷贝
对于这类类型数据,我们可通过下面方法查看数据类型,他们都属于Object类型
var obj = new Date()
console.log(Object.prototype.toString.call(obj).slice(8, -1) == "Date") //true
console.log(c.instanceof Date) //true
则可封装深拷贝方法
function deepCopy(obj) {
var o
switch (typeof (obj)) {
case 'undefined':
break;
case "string":
o = obj + ""
break;
case 'boolean':
o = obj
break;
case 'number':
o = obj + 0
break;
case "object":
if (obj == null) {
o = null
} else {
if (Object.prototype.toString.call(obj).slice(8, -1) == "Array") {
//数组
o = []
for (let index = 0; index < obj.length; index++) {
o.push(deepCopy(obj[index]))
}
} else if (Object.prototype.toString.call(obj).slice(8, -1) == "Date") {
//时间类型
o = new Date();
o.setTime(obj.getTime());
} else if (Object.prototype.toString.call(obj).slice(8, -1) == "Object") {
o = {}
for (const key in obj) {
o[key] = deepCopy(obj[key])
}
}else if(Object.prototype.toString.call(obj).slice(8, -1) == "RegExp"){
o = new RegExp(obj)
}else {
o = obj
}
}
break;
default:
o = obj;
break;
}
return o
}
改进
//深拷贝数据
export function deepCopy(data) {
//string,number,bool,null,undefined,symbol
//object,array,date
if (data && typeof data === "object") {
//针对函数的拷贝
if (typeof data === "function") {
let tempFunc = data.bind(null);
tempFunc.prototype = deepCopy(data.prototype);
return tempFunc;
}
switch (Object.prototype.toString.call(data)) {
case "[object String]":
return data.toString();
case "[object Number]":
return Number(data.toString());
case "[object Boolean]":
return new Boolean(data.toString());
case "[object Date]":
return new Date(data.getTime());
case "[object Array]":
var arr = [];
for (let i = 0; i < data.length; i++) {
arr[i] = deepCopy(data[i]);
}
return arr;
//js自带对象或用户自定义类实例
case "[object Object]":
var obj = {};
for (let key in data) {
//会遍历原型链上的属性方法,可以用hasOwnProperty来控制 (obj.hasOwnProperty(prop)
obj[key] = deepCopy(data[key]);
}
return obj;
}
} else {
//string,number,bool,null,undefined,symbol
return data;
}
}