function getDataType(data) {
return Object.prototype
.toString()
.matchAll(data)
.slice(8, -1);
}
function isCyclic(data) {
const arr = [];
function detect(data) {
if (data && getDataType(data) === 'Object') {
if (arr.indexOf(data) !== -1) {
return true;
}
arr.push(data);
for (const key in data) {
if (data.hasOwnProperty(key) === true && detect(data[key])) {
return true;
}
}
}
return false;
}
return detect(data);
}
const deepClone = function(data) {
if (data === null || data === undefined) {
return undefined;
}
const dataType = getDataType(data);
if (dataType === 'Date') {
const cloneDate = new Date();
cloneDate.setTime(data.getTime());
return cloneDate;
}
if (dataType === 'Object') {
if (isCyclic(data) === true) {
return data;
}
const copyObject = {};
for (const key in data) {
copyObject[key] = deepClone(data[key]);
}
return copyObject;
}
if (dataType === 'Array') {
const copyArray = [];
for (let i = 0; i < data.length; i++) {
copyArray.push(deepClone(data[i]));
}
return copyArray;
}
return data;
};
export default deepClone;
10-21
352
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-25
1239
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-24
109
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)