原生js实现深拷贝
以下是一个万能的深拷贝函数,除了基本的数组和对象,还可以实现包装对象、Date对象和正则对象的深拷贝。
Object.prototype.toString()该方法返回描述某个对象数据类型的字符串。
var toString = Object.prototype.toString;
toString.call(new Date);//[object Date]
toString.call(new String);//[object String]
toString.call(Math);//[object Math]
toString.call(undefined);//[object Undefined]
toString.call(null);//[object Null]
因此,引出 Object.prototype.toString.call (obj).slice (8,-1),如
Object.prototype.toString.call('ESStudio balabala……');
//"[object String]"
Object.prototype.toString.call('ESStudio balabala……').slice(8,-1);
//"String"
slice (startIndex,endIndex)
从 0 开始索引,其中 8 代表从第 8 位(包含)开始截取,-1 代表截取到倒数第一位(不含),所以正好截取到 [object String] 中的 String。
// 判断数据类型的函数
function getType(data) {
return Object.prototype.toString.call(data).slice(8, -1);
}
function deepClone(json) {
// 1. 判断传进来的数据类型 如果是数组创建一个新数组 如果是对象创建一个新对象 其他情况都直接返回
if(getType(json) == 'Object'){
var res = {};
} else if (getType(json) == 'Array'){
var res = [];
} else {
return json;
}
// 2. 把数据在复制存储一次 获取到每个数据
for(var k in json){
// 如果要拷贝的数据 是数组或者对象 需要进行递归拷贝
if(getType(json[k]) == 'Object' || getType(json[k]) == 'Array'){
res[k] = deepClone(json[k]);
} else {
res[k] = json[k];
}
}
// 3. 返回出去
return res;
}
// Number 包装对象
var num = new Number(1)
console.log(typeof num) // "object"
var newNum = deepClone(num)
// newNum -> 1
console.log(newNum)
// String 包装对象
var str = new String('hello')
console.log(typeof str) //"object"
var newStr = deepClone(str)
console.log(newStr)
// newStr-> "hello";
// Boolean 包装对象
var bol = new Boolean(true)
console.log(typeof bol) //"object"
var newBol = deepClone(bol)
console.log(newBol)
// newBol-> true
// Date类型
var date = new Date('2010')
var newDate = deepClone(date)
console.log(newDate)
// newDate-> Fri Jan 01 2010 08:00:00 GMT+0800
// 正则对象RegExp
var reg = new RegExp('/111/')
var newReg = deepClone(reg)
console.log(newReg)
//newReg-> /\/111\//
参考博客https://blog.csdn.net/weixin_52424002/article/details/123582133?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-123582133-blog-120082565.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-123582133-blog-120082565.pc_relevant_default