Appearance
实现Array.prototype.flat()
题目链接
https://bigfrontend.dev/problem/implement-Array-prototype.flat
题目说明
js
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]
实现一个flat函数,第二个参数是要拍平的次数
题目解析
- 默认第二个参数是1
- 使用while循环,每次循环的时候拍平一次,直到第二个参数为0
- 如果已经内有数组了,跳出循环直接输出
js
/**
* @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
}