簡體   English   中英

使用 forEach 循環遍歷另一個數組以獲取條件

[英]Looping through another array for conditions using forEach loop

我創建了一個名為 checkLength(input, min, max) 的函數,它接受用戶名和密碼輸入,如下所示。

checkLength(username, 3, 15);
checkLength(password, 8, 25);

但是,我希望傳入一個 inputArray、minArray、maxArray 以減少使用 forEach 循環的重復性。 但似乎 forEach 循環一次只能接收一個數組。 關於如何改進這一點的任何建議?

checkLength2([username,password], [3,8], [8,15])

function checkLength2 (inputArray, minArray, maxArray, i=0) {
inputArray.forEach(input => {
    if (input.value < minArray[i]) {
        //another error function
        i++;
    }
});}

您應該嘗試forEach循環中的索引。

function checkLength2 (inputArray, minArray, maxArray) {
  inputArray.forEach((input, i) => {
      if (input.value < minArray[i]) {
          // do something
      } else if (input.value > maxArray[i]) {
          // do something else
      }
  });
}

如果你想顯示相同的消息,你可以試試這個。 否則你可以使用 if/else 語句來檢查 minArray 和 maxArray

function checkLength2(inputArray, minArray, maxArray, i = 0) {    
  for (let index = 0; index <= inputArray.length; index++) {    
    if (inputArray[index].value < minArray[index] && inputArray[index].value>maxArray[index]) {    
      //error
    }
  }
}

暫無
暫無

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

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