let arr = [1, 2, [3, 4, [5, 6]]]
// 循环递归
let flatten1 = function (arr) {
let ret = []
for (let i=0; i<arr.length; i++) {
if (Array.isArray(arr[i])) {
ret = ret.concat(flatten1(arr[i]))
} else {
ret.push(arr[i])
}
}
return ret
}
// console.log(flatten1(arr));
// reduce循环递归
let flatten2 = function (arr) {
return arr.reduce((result, item) => {
return result.concat(Array.isArray(item) ? flatten2(item) : item)
}, [])
}
// console.log(flatten2(arr));
// toString方法
let flatten3 = function (arr) {
return arr.toString().split(',').map(item => +item)
}
// console.log(flatten3(arr));
// es6扩展运算符
let flatten4 = function (arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr)
}
return arr
}
console.log(flatten4(arr));
// es6自带
function f5(arr) {
return arr.flat(Infinity)
}
// 使用栈
function f7(arr) {
const stack = [...arr]
const ret = []
while(stack.length) {
const next = stack.pop()
if(Array.isArray(next)) {
stack.push(...next)
} else {
ret.push(next)
}
}
return ret.reverse();
}
// 解构运算原理,generator
function* flatten(arr) {
for (const item of arr) {
if(Array.isArray(item)){
yield* f6(item)
} else {
yield item
}
}
}
var arr = [1, 2, [3, 4, [5, 6]]];
const flattened = [...flatten(arr)];