1. function deepClone(val) {
    2. const type = getType(val);
    3. // 如果不是数组或对象,不需要递归,则直接返回
    4. if (type !== 'Array' && type !== 'Object') {
    5. return val;
    6. }
    7. // 如果是数组或对象,构造一个新的,遍历复制
    8. let res = type === 'Object' ? {} : [];
    9. for (let key in val) {
    10. const subVal = val[key];
    11. const subType = getType(subVal);
    12. if (subType !== 'Object' && subType !== 'Array') {
    13. res[key] = subVal;
    14. } else {
    15. res[key] = deepClone(subVal);
    16. }
    17. }
    18. return res;
    19. // 获取类型工具函数
    20. function getType(val) {
    21. return Object.prototype.toString.call(val).slice(8, -1);
    22. }
    23. }
    24. // const arr1 = [1, 2, 3, 4, 5]
    25. // const arr2 = deepClone([1, 2, 3, 4, 5])
    26. // arr1[1] = 10
    27. // console.log(arr1, arr2)
    28. const obj1 = { a: 1, b: 2, c: 3, d: 4, e: { a: 1, b: 2, c: 3 } }
    29. const obj2 = deepClone(obj1)
    30. obj1.e.a = 1000
    31. console.log(obj1, obj2)

    参考
    https://www.cxymsg.com/guide/jsWritten.html#%E5%AE%9E%E7%8E%B0%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0%EF%BC%88debounce%EF%BC%89
    https://www.yuque.com/chenyubo/knowledge-map/qus818#OP8CP