返回一個包含 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]
廣告