• 数组扁平化的方法


    1. JavaScript 中,有多种方法可以将嵌套的数组扁平化,即将多层嵌套的数组转换为一个一维数组。下面介绍几种常用的方法:
    2. 方法一:使用递归
    3. function flattenArray(arr) {
    4. let result = [];
    5. for (let i = 0; i < arr.length; i++) {
    6. if (Array.isArray(arr[i])) {
    7. result = result.concat(flattenArray(arr[i]));
    8. } else {
    9. result.push(arr[i]);
    10. }
    11. }
    12. return result;
    13. }
    14. // 示例用法
    15. const nestedArray = [1, 2, [3, 4, [5, 6]]];
    16. const flattenedArray = flattenArray(nestedArray);
    17. console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
    18. 方法二:使用 `Array.prototype.flat()` 方法(ES2019+)
    19. const nestedArray = [1, 2, [3, 4, [5, 6]]];
    20. const flattenedArray = nestedArray.flat(Infinity);
    21. console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
    22. 方法三:使用 `Array.prototype.reduce()` 方法
    23. const nestedArray = [1, 2, [3, 4, [5, 6]]];
    24. const flattenedArray = nestedArray.reduce((acc, current) => {
    25. return acc.concat(Array.isArray(current) ? flattenArray(current) : current);
    26. }, []);
    27. console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
    28. 这些方法都能够将嵌套的数组扁平化,但使用时需要根据具体情况选择最适合的方法。其中,递归方式对于嵌套层数较深的数组可能会有性能上的影响,而 `Array.prototype.flat()` 方法和 `Array.prototype.reduce()` 方法则是较为简洁高效的处理方式

  • 相关阅读:
    小家电设计:小型家用电器的设计方向
    DevOps 笔记
    Docker搭建redis集群
    C数据结构-堆的实现思路和堆排序的实现
    Mybatis速成(二)
    Kotlin挂起函数整理-基础
    linux下的永久保存行号
    微软发布2023年10月补丁,修复了103个缺陷,包括2个活跃的漏洞利用
    C++课程设计——图书管理系统
    纯手写http服务器
  • 原文地址:https://blog.csdn.net/kuang_nu/article/details/133211910