簡體   English   中英

使用奇數索引返回奇數 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 的奇數索引處獲取奇數的最佳方法? 必須保留數字的順序。

  • 所以你在這里做錯的是你沒有檢查索引。 這就是為什么你沒有得到想要的 output。
  • 為了解決您的問題,我所做的是我使用了 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]));

У您需要使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM