JSON.parse(JSON.stringify(arr/obj)): 数组或对象深拷贝, 但不能处理函数
// 1.检测数据类型
function getDataType(data) {
let dataType = Object.prototype.toString.call(data).slice(8, -1);
if (dataType === 'Null') {
return 'Null';
} else if (dataType === 'Undefined') {
return 'Undefined';
} else {
return dataType;
}
}
// 2.深拷贝
function deepCopy(obj){
let objType = getDataType(obj);
let res;
if(objType === 'Object') {
res = {};
}else if(objType === 'Array') {
res = [];
}else {
return obj;
}
//遍历对象
for(let key in obj){
let value = obj[key];
if(getDataType(value) === "Object" || "Array"){
res[key] = deepCopy(value);
}else{
res[key] = obj[key];
}
}
return res;
}
let num = 1;
let num2 = deepCopy(num);
console.log(num2);
let str = 'abc';
let str2 = deepCopy(str);
console.log(str2);
let flag = true;
let flag2 = deepCopy(flag);
console.log(flag2);
let null1 = null;
let null2 = deepCopy(null1);
console.log(null2);
let undefined1 = undefined;
let undefined2 = deepCopy(undefined1);
console.log(undefined2);
let arr1 = [1,2,3,4];
let arr2 = deepCopy(arr1);
console.log(arr2);
let arr3 = [[1,2,3,4],[5,6,[7,8]]];
let arr4 = deepCopy(arr3);
console.log(arr4);
let obj1 = {
name: 'aa',
age: 18
};
let obj2 = deepCopy(obj1);
console.log(obj2);
let obj3 = {
name: 'aa',
age: 18,
say: function(){
console.log('say');
},
options: {
a1: 'a1',
a2: 'a2'
}
};
let obj4 = deepCopy(obj3);
console.log(obj4);