有一个数组
arr = [1, 2, [3, 4], 5]
要将它拍平,可使用 Array.prototype.concat 方法
Array.prototype.concat.apply([], arr)// 等价于Array.prototype.concat.call([], ...arr)// 等价于[].concat(...arr)// 即[].concat(1, 2, [3, 4], 5)
对于嵌套更深的数组,则可以使用递归
function flatten(arr) {const isDeep = arr.some(item => item instanceof Array)if (!isDeep) {return arr}const res = Array.prototype.concat.apply([], arr)return flatten(res)}console.log(flatten([1, 2, [3, [4, 5, [6, 7]]], 8, [9, 10]]))
