1. 直接利用Array的flat()方法:
console.log([2, -5, 6, [6, -5, [2, 5], [8, 10, [6, 8], -3], 2], 5].flat(Infinity))
2. 一个简单好记得方法:
var arr = [12, 23, 34, [6, [6], [6,[7,[8]]]], [5,[5]], [4, [7]], [4, [[3]]], 45, 6];
arr.toString().split(",").map(function(item){
return Number(item)
})
arr.toString().split(',').map(Number);
3. 利用递归纯手写
function flatten(arr){
var newArr = [];
function fn(arr){
for (let i = 0; i < arr.length; i++) {
// console.log(arr[i],arr[i].length)
if(arr[i].length){ //Array.isArray(arr[i])
fn(arr[i])
}else{
newArr.push(arr[i])
}
}
}
fn(arr)
// return newArr; //[2, -5, 6, 6, -5, 2, 5, 8, 10, 6, 8, -3, 2, 5]
return newArr.sort(function(a,b){
return a - b;
}) ////[-5, -5, -3, 2, 2, 2, 5, 5, 6, 6, 6, 8, 8, 10]
}
console.log(flatten([2, -5, 6, [6, -5, [2, 5], [8, 10, [6, 8], -3], 2], 5]))
function flatten(arr){
if(arr.some(item=>Array.isArray(item))){
let newArr = [];
arr.forEach(function(item,index,arr){
if(Array.isArray(item)){
newArr = newArr.concat(item)
}else{
newArr.push(item)
}
})
return flatten(newArr)
}
return arr.sort(function(a,b){
return a - b;
})
}
console.log(flatten([ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]))
//[1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 12, 13, 14]