从 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]
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短