返回一个包含 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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP