将[1,2,[3,4,[5,6],7],8]转成怎[1,2,3,4,5,6,7,8]
1、最简单方法
[1,2,[3,4,[5,6],7],8].toString().split(',')
// ->["1", "2", "3", "4", "5", "6", "7", "8"]
2、reduce递归
function toArray(a){
return a.reduce((res,current)=>{
return Array.isArray(current)?[...res,...toArray(current)]:[...res,current]
},[])
}
toArray([1,2,[3,4,[5,6],7],8])
// -->[1, 2, 3, 4, 5, 6, 7, 8]
3 、字符串
JSON.stringify([1,2,[3,4,[5,6],7],8]).replace(/\[|\]/g,'').split(',')
// -->[1, 2, 3, 4, 5, 6, 7, 8]