话不多说,直接上代码。
个人认为比较好记忆的两种写法:
const result = [];
function flatten(arr, currentDepth) {
for (const item of arr) {
if (Array.isArray(item) && currentDepth > 0) {
flatten(item, currentDepth - 1);
} else {
result.push(item);
}
}
}
return result;
function flat(arr, depth = 1) {
while (depth > 0) {
arr = [].concat(...arr);
depth--;
}
return arr;
}