3. 实现Array.prototype.flat()

frontend

# 题目链接

https://bigfrontend.dev/problem/implement-Array-prototype.flat (opens new window)

# 题目说明

const arr = [1, [2], [3, [4]]];

flat(arr)
// [1, 2, 3, [4]]

flat(arr, 1)
// [1, 2, 3, [4]]

flat(arr, 2)
// [1, 2, 3, 4]
1
2
3
4
5
6
7
8
9
10

实现一个flat函数,第二个参数是要拍平的次数

# 题目解析

  • 默认第二个参数是1
  • 使用while循环,每次循环的时候拍平一次,直到第二个参数为0
  • 如果已经内有数组了,跳出循环直接输出
/**
 * @param { Array } arr
 * @param { number } depth
 * @returns { Array }
 */
function flat(arr, depth = 1) {
  let res = [...arr]
  while(depth && res.some(item => Array.isArray(item))) {
    depth--
    res = [].concat(...res)
  }
  return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
更新时间: 2022-11-21 16:22