带层数的扁平化实现了下 function flatten(arr,lev) { var arr1 = [] if(lev == 0) { // console.log(arr,arr1,11) arr1 = arr1.concat(arr) // console.log(arr1,1223) } else { for(let i = 0; i < arr.length; i++) { if(Array.isArray(arr[i]) === true){ arr1 = arr1.concat(flatten(arr[i], lev-1)) // console.log(arr1,223) } else { arr1.push(arr[i]) } } } return arr1 } var ary = [1,2,[3,[4,5]],6,[7,8]] console.log(flatten(ary,2))

相关推荐

牛客网
牛客企业服务