You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constflatten=(arr=[])=>{if(!Array.isArray(arr))thrownewError('param is not Array, it cannot be flatten')const{ length }=arrfor(leti=0;i<length;i++){if(Array.isArray(arr[i]))returnflatten(arr.slice(0,i).concat(arr[i],arr.slice(i+1)))}returnarr}
实现方式二
constflatten=(arr=[],result=[])=>{if(!Array.isArray(arr))thrownewError('param is not Array, it cannot be flatten')const{ length }=arrfor(leti=0;i<length;i++){if(Array.isArray(arr[i])){result=result.concat(flatten(arr[i]))continue}result.push(arr[i])}returnresult}
作用
其实,这个妹啥好说的,就是把多维数组降为一维,直接贴代码吧
示例
对于代码风格来讲,本人更倾向于第一种,但是性能来讲,第二种肯定更好~
原理
迭代+递归
The text was updated successfully, but these errors were encountered: