从数组返回奇数或偶数 [英] Returning an odd or even number from array
问题描述
仅需要帮助您确定我在此Codewar挑战中做错了什么.
Just need help in identifying what I am doing wrong on this codewar challenge.
我意识到这对某些人来说可能很容易,但是请注意,我只是Java语言的初学者.
I realize this may be easy for some but please note I am just a beginner with Javascript.
挑战:
您将获得一个数组(长度至少为3,但是 可能非常大)包含整数.数组要么完全是 由奇数整数组成或完全由偶数整数组成 除了单个整数N.编写一个将数组作为 一个参数并返回N.
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns N.
例如:
[2, 4, 0, 100, 4, 11, 2602, 36]
应该返回11
.
[160, 3, 1719, 19, 11, 13, -21]
应该返回160
.
我的代码:
function findOutlier(integers){
var even = [];
var odd = [];
for (var i = 0; i < integers; i++) {
if (integers[i] % 2 === 0) {
even.push(integers[i]);
} else {
odd.push(integers[i]);
}
if (even.length === 1) {
return even;
} else {
return odd;
}
}
}
推荐答案
另一种可能的方式:
function myFunction(integers) {
var odds = integers.filter(function(num) {return num % 2});
var evens = integers.filter(function(num) {return !(num % 2)});
return evens.length == 1 ? evens[0] : odds[0];
}
您可以查看此 CodePen演示 在Mocha中测试功能.
You can check out this CodePen Demo to test the function in Mocha.
这篇关于从数组返回奇数或偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!