如何从数组中删除偶数? [英] How can I remove even numbers from an array?
本文介绍了如何从数组中删除偶数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要删除该数组的偶数
I need to remove the even numbers for this array
function removeEvens(numbers) {
}
/* Do not modify code below this line */
const oddNumbers = removeEvens([1, 2, 3, 4, 5]);
console.log(oddNumbers, `<-- should equal [1, 3, 5]`);
推荐答案
第一步是检查偶数的方法-您可以使用模数运算符(%
)来检查余数当除以2时为0,表示数字为偶数.接下来,您可以过滤该数组仅包含通过此测试的数字:
The first step is how you check for evens - you can do this using the modulus operator (%
) to see if the remainder when divided by 2 is 0, meaning that the number is even. Next you can filter the array to include only the numbers which pass this test:
function removeEvens(numbers) {
return numbers.filter(n => n % 2 !== 0); // if a number is even, remove it
}
const oddNumbers = removeEvens([1, 2, 3, 4, 5]);
console.log(oddNumbers);
这篇关于如何从数组中删除偶数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文