简体   繁体   English

使用奇数索引返回奇数 JavaScript

[英]Using odd index to return odd numbers JavaScript

I'm trying to solve a problem on a testing website and I'm getting confused on trying to find the odd numbers from a passed in array at odd index.我试图在一个测试网站上解决一个问题,我对试图从奇数索引处传入的数组中找到奇数感到困惑。

Code I have so far;到目前为止我的代码;

    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]));

In the above example I want it to return [3, 7, 11] but I can't figure out how.在上面的示例中,我希望它返回 [3, 7, 11] 但我不知道如何。 Can you please fix my code and explain to me the best way of getting an odd number at an odd index from a passed in array to the function?您能否修复我的代码并向我解释从传入数组到 function 的奇数索引处获取奇数的最佳方法? The order of the numbers has to be retained.必须保留数字的顺序。

  • So what you are doing wrong here is that you are not checking the index.所以你在这里做错的是你没有检查索引。 that's why you are not getting desired output.这就是为什么你没有得到想要的 output。
  • To solve your problem what I did is that I used Array's filter method and then first check if the index is odd or not, if it's odd then I am checking whether the value is odd or not is its odd then we return the value.为了解决您的问题,我所做的是我使用了 Array 的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]));

Уou need to use an index to determine if it is odd or not. У您需要使用index来确定它是否是奇数。 But you can also reduce the amount of code and increase readability if use .filter但是如果使用.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 }

we can make this way too我们也可以这样做

filter will give itself true values only we no need to check values if or else过滤器只会给自己真正的值,否则我们不需要检查值

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM