1. const deepClone = (target, cache = new Map()) => {
    2. const isObject = (obj) => typeof obj === 'object' && obj !== null
    3. if (isObject(target)) {
    4. // 解决循环引用
    5. const cacheTarget = cache.get(target)
    6. // 已经存在直接返回,无需再次解析
    7. if (cacheTarget) {
    8. return cacheTarget
    9. }
    10. let cloneTarget = Array.isArray(target) ? [] : {}
    11. cache.set(target, cloneTarget)
    12. for (const key in target) {
    13. if (target.hasOwnProperty(key)) {
    14. const value = target[ key ]
    15. cloneTarget[ key ] = isObject(value) ? deepClone(value, cache) : value
    16. }
    17. }
    18. return cloneTarget
    19. } else {
    20. return target
    21. }
    22. }
    23. const target = {
    24. field1: 1,
    25. field2: undefined,
    26. field3: {
    27. child: 'child'
    28. },
    29. field4: [2, 4, 8],
    30. f: { f: { f: { f: { f: { f: { f: { f: { f: { f: { f: { f: {} } } } } } } } } } } },
    31. };
    32. target.target = target;
    33. const result1 = deepClone(target);
    34. console.log(result1)