Open senfish opened 3 years ago
function flat(arr, depth = 1) {
return depth > 0 ?
arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flat(cur, depth - 1) : cur);
}, []) :
arr.slice();
}
function flat(list, depth = 1) {
let result = [];
for(let i = 0; i < list.length; i++) {
let value = list[i];
if(Array.isArray(value) && depth > 0) {
result = result.concat(flat(value, depth - 1))
} else {
result.push(value);
}
}
return result;
}
实现一个flat函数,扁平化数组,接收一个arr数组和一个depth参数,如果不传,默认为1;