deepClone.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // 判断arr是否为一个数组,返回一个bool值
  2. function isArray(arr) {
  3. return Object.prototype.toString.call(arr) === '[object Array]';
  4. }
  5. // 深度克隆
  6. function deepClone(obj, cache = new WeakMap()) {
  7. if (obj === null || typeof obj !== 'object') return obj;
  8. if (cache.has(obj)) return cache.get(obj);
  9. let clone;
  10. if (obj instanceof Date) {
  11. clone = new Date(obj.getTime());
  12. } else if (obj instanceof RegExp) {
  13. clone = new RegExp(obj);
  14. } else if (obj instanceof Map) {
  15. clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)]));
  16. } else if (obj instanceof Set) {
  17. clone = new Set(Array.from(obj, value => deepClone(value, cache)));
  18. } else if (Array.isArray(obj)) {
  19. clone = obj.map(value => deepClone(value, cache));
  20. } else if (Object.prototype.toString.call(obj) === '[object Object]') {
  21. clone = Object.create(Object.getPrototypeOf(obj));
  22. cache.set(obj, clone);
  23. for (const [key, value] of Object.entries(obj)) {
  24. clone[key] = deepClone(value, cache);
  25. }
  26. } else {
  27. clone = Object.assign({}, obj);
  28. }
  29. cache.set(obj, clone);
  30. return clone;
  31. }
  32. export default deepClone;