思路:

很简单,和我们之前做的数组扁平化差不多,也就多一个传入参数depth 表示要展开的深度,话不多说,直接上代码

(1)直接递归版

  1. let arr = [1, [2, 3], [4, [5, [6, [7, 8]]]]]
  2. // 传入depth参数,默认值为 1
  3. Array.prototype._flat = function (depth = 1) {
  4. // 当到达指定深度,或 当前对象不是数组时,直接返回这个值
  5. if(depth < 1 || !Array.isArray(this)){
  6. return this
  7. }
  8. let res = []
  9. for (const item of this) {
  10. if (Array.isArray(item)) {
  11. res = res.concat(item._flat(depth - 1))
  12. } else {
  13. res.push(item)
  14. }
  15. }
  16. return res
  17. }
  18. console.log(arr._flat());
  19. console.log(arr._flat(2));
  20. console.log(arr._flat(4));

image.png

(2)reduce版

  1. let arr = [1, [2, 3], [4, [5, [6, [7, 8]]]]]
  2. Array.prototype._flat = function (depth = 1) {
  3. if (depth < 1 || !Array.isArray(this)) {
  4. return this
  5. }
  6. return this.reduce((prev, curr) => {
  7. if (Array.isArray(curr)) {
  8. return prev.concat(curr._flat(depth - 1))
  9. } else {
  10. return prev.concat(curr)
  11. }
  12. }, [])
  13. }
  14. console.log(arr._flat());
  15. console.log(arr._flat(2));
  16. console.log(arr._flat(4));

image.png

在使用flat时,如何直接全部展开

我们可以直接参考MDN,传入 depth 为 Infinity

  1. let arr = [1, [2, 3], [4, [5, [6, [7, 8]]]]]
  2. console.log(arr._flat(Infinity));

image.png

使用flat时,数组内的空项会被移除

  1. let arr = [1, 2, , 4, 5];
  2. console.log(arr._flat());

image.png

关于flat的更多的详情,可以参考MDN-flat