返回一個包含 JavaScript 輸入陣列中最後 n 個偶數的陣列


問題

我們要求用 JavaScript 編寫一個函式,該函式將一個數字陣列作為第一個引數,一個數字作為第二個引數。

我們的函式應選取並返回一個數組,其中包含輸入陣列中存在的最後 n 個偶數。

示例

以下是程式碼 −

 線上演示

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const num = 3;
const pickEvens = (arr = [], num = 1) => {
   const res = [];
   for(let index = arr.length - 1; index >= 0; index -= 1){
      if (res.length === num){
         break;
      };
      const number = arr[index];
      if (number % 2 === 0){
         res.unshift(number);
      };
   };
   return res;
};
console.log(pickEvens(arr, num));

輸出

[4, 6, 8]

更新於: 20-Apr-2021

145 次瀏覽

開啟你的 職業生涯

完成本課程即可獲得認證

開始
廣告