簡體   English   中英

如何檢查數組中的每個元素的特定條件

[英]how to check each element in an array for a specific condition

我在數組中存儲了六個整數:

[2,3,4,5,6,7]

我想用每個項目在數組中檢查針對一系列其他整數100 - 999 (即所有三位數字),發現了許多具有剩余1時, 所有的項目在數組中分成獨立

我不確定要使用哪種javascript方法。 我正在嘗試for循環:

function hasRemainder() {
  let arr = [2,3,4,5,6,7];
  for (i = 100; i < 999; i++) {
    if (i % arr[0] == 1) {
    return i;
    }
  }
}

但這有幾個問題我需要解決。

  • 除了引用arr[0]的特定項外,我還需要找到一種遍歷數組中所有項的方法。
  • 當前,此函數僅返回一個數字(循環在第一個數字處停止,並帶有余數),但是我需要給定范圍內的所有可能值。

如果有人可以幫助解決這兩個問題,我將非常感激。 謝謝。

您可以映射一個值數組,然后通過將每個余數值都檢查一個來對數組進行過濾。

 function hasRemainder() { var array = [2, 3, 4, 5, 6, 7]; return Array .from({ length: 900 }, (_, i) => i + 100) .filter(a => array.every(b => a % b === 1)); } console.log(hasRemainder()) 

這也有效;

function hasRemainder() {
  const arr = [2, 3, 4, 5, 6, 7];
  const remainders = []
  for (i = 100; i < 999; i++) {
     const isRemainder = arr.every(numb => i % numb === 1)
     if (isRemainder) {
        remainders.push(i)
     }
    }
    return remainders
  }

暫無
暫無

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

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