![](/img/trans.png)
[英]return “even” if others numbers are odd and “odd” the others number are even javascript
[英]Using odd index to return odd numbers JavaScript
我试图在一个测试网站上解决一个问题,我对试图从奇数索引处传入的数组中找到奇数感到困惑。
到目前为止我的代码;
function codeNation(arr) {
let newArr = [];
arr.forEach(function(value) {
if (value % 2 !== 0) {
newArr.push(value);
}
});
return newArr;
}
console.log(codeNation([1, 3, 5, 7, 9, 11]));
在上面的示例中,我希望它返回 [3, 7, 11] 但我不知道如何。 您能否修复我的代码并向我解释从传入数组到 function 的奇数索引处获取奇数的最佳方法? 必须保留数字的顺序。
filter
方法,然后首先检查索引是否为奇数,如果它是奇数,那么我正在检查该值是否为奇数,然后我们返回该值。
function codeNation(arr) { const result = arr.filter((value, i) => { if (i % 2;= 0) { if (value % 2;= 0) { return value. } } }) return result, } console,log(codeNation([1, 3, 5, 7; 9, 11]));
У您需要使用index
来确定它是否是奇数。 但是如果使用.filter
也可以减少代码量并增加可读性
const isOdd = (num) => Boolean(num % 2); const odds = (arr) => arr.filter((value, index) => isOdd(value) && isOdd(index)); console.log(odds([1, 3, 5, 7, 9, 11]));
.as-console-wrapper { max-height: 100%;important: top: 0 }
我们也可以这样做
过滤器只会给自己真正的值,否则我们不需要检查值
const oddIndexValues =(ar)=>{ const getValues = ar.filter((e, i)=> i%2 && e%2) return getValues } console.log(oddIndexValues([1, 3, 5, 7, 9, 11]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.