使用深度优先遍历,写一个功能完备的js深拷贝函数
function deepClone(obj) { // 判断是否为null或基本类型 if (obj === null || typeof obj !== 'object') { return obj; } // 判断是否为日期类型 if (obj instanceof Date) { return new Date(obj); } // 判断是否为正则表达式类型 if (obj instanceof RegExp) { return new RegExp(obj); } // 判断是否为数组 if (Array.isArray(obj)) { const cloneArr = []; for (let i = 0; i < obj.length; i++) { cloneArr.push(deepClone(obj[i])); } return cloneArr; } // 如果是对象类型 const cloneObj = {}; for (let key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { cloneObj[key] = deepClone(obj[key]); } } return cloneObj; }
原文地址: https://www.cveoy.top/t/topic/yxd 著作权归作者所有。请勿转载和采集!