使用 JavaScript 中的迴圈和遞迴對陣列進行扁平化


我們需要編寫一個 JavaScript 陣列函式,這個函式將帶有一個巢狀陣列和 false 值,並返回一個數組,其中包含陣列中所有元素,且無任何巢狀。

例如:如果輸入是 −

const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];

則輸出應為 −

const output = [1, 2, 3, 4, 5, false, 6, 5, 8, null, 6];

因此,讓我們為此函式編寫程式碼 −

程式碼如下 −

const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];
const flatten = function(){
   let res = [];
   for(let i = 0; i < this.length; i++){
      if(Array.isArray(this[i])){
         res.push(...this[i].flatten());
      }else{
         res.push(this[i]);
      };
   };
   return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());

輸出

控制檯中的輸出將為 −

[
   1, 2, 3, 4,
   5, 5, false, 6,
   5, 8, null, 6
]

更新時間:2020 年 10 月 20 日

541 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.