1. let arr = [[1], [2, 3], [4, 5, 6, [7, 8, [9, 10, [11]]]], 12]
  2. // 1. 通过toString()的方式
  3. const a = arr
  4. .toString()
  5. .split(',')
  6. .map((item) => +item)
  7. // console.log(a)
  8. // 2. 使用JSON.stringify + 正则替换
  9. const e = JSON.stringify(arr)
  10. .replace(/\[|\]/gi, '')
  11. .split(',')
  12. .map((item) => +item)
  13. console.log(e)
  14. // 3. 通过自带的函数来解决
  15. const b = arr.flat(Infinity)
  16. // console.log(b)
  17. // 4. 使用循环 + 解构的方式
  18. let c = arr
  19. while (c.some((item) => Array.isArray(item))) {
  20. c = [].concat(...c)
  21. }
  22. // console.log(c)
  23. // 5. 使用reduce + 递归函数解决方案
  24. let d = arr
  25. const decon = function decon(arr) {
  26. return arr.reduce((pre, cur) => {
  27. if (Array.isArray(cur)) {
  28. pre = pre.concat(decon(cur))
  29. } else {
  30. pre = pre.concat(cur)
  31. }
  32. return pre
  33. }, [])
  34. }
  35. d = decon(d)
  36. // console.log(d)

1. 要点分析

  • 使用toSring() + split分割数组
  • 使用JSON.stringify() + 正则替换[] + split分割数组
  • 使用自带的Api
  • 使用循环 + 解构方式
  • 使用reduce + 递归的方式