簡體   English   中英

使用 2 個 arguments 的 function 獲取數組的每個第 n 個元素

[英]Get every nth element of array with a function of 2 arguments

我一直在努力應對一些挑戰,這是我無法解決的挑戰之一。 這個任務是這樣的:

  • 編寫一個 function,它將一個數組 (a) 和一個值 (n) 作為 arguments
  • 將每個第 n 個元素保存在一個新數組中
  • 返回新數組

這是我期待的 output:

console.log(myFunction([1,2,3,4,5,6,7,8,9,10],3))    //Expected [3,6,9]
console.log(myFunction([10,9,8,7,6,5,4,3,2,1],5))    //Expected [6,1]
console.log(myFunction([7,2,1,6,3,4,5,8,9,10],2))    //Expected [2,6,4,8,10]

這是我試圖弄清楚的,但事實並非如此:

 function nthElementFinder(a, n) { return a.filter((e, i, a) => { const test = i % n === 0; return test; }); } console.log(nthElementFinder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

你幾乎擁有它。 Javascript(和大多數其他語言)中的數組是從 0 開始的,這意味着第一個 position 的索引 = 0。所以您的 function 只需在每次迭代時將 1 添加到索引中

function nthElementFinder(a, n) {
  return a.filter((e, i, a) => {
    const test = (i + 1) % n === 0 ;
    return test;
  });
}
console.log(nthElementFinder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

除了過濾解決方案之外,您還可以迭代並將每個第 n 個項目推送到一個新數組。 這種方法不會訪問所有項目,而只會訪問第 n 個項目。

 function nthElementFinder(a, n) { const result = []; let i = n - 1; while (i < a.length) { result.push(a[i]); i += n; } return result; } console.log(nthElementFinder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));

@Bhaskar Deb,因為無論如何您都在遍歷數組,所以您(幾乎)免費獲得第 n 個元素選擇。 這不會運行,因為唯一相關的位是循環內的剩余部分。

function whatever(a, n) {


      let arr   = a,
          i     = a.length - 1,
          nth   = n;


      do {

          if(i % nth === 0) {
//           do your nth object stuff here
          }

//           do your array stuff here

        i--;

      } while (i > -1);


}

whatever(yourArray, n);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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