简体   繁体   English

使用 forEach 循环遍历另一个数组以获取条件

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

I've created a function called checkLength(input, min, max) which takes in a username and password input as shown below.我创建了一个名为 checkLength(input, min, max) 的函数,它接受用户名和密码输入,如下所示。

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

However, I'm looking to pass in an inputArray, minArray, maxArray to reduce the repetitiveness using a forEach loop.但是,我希望传入一个 inputArray、minArray、maxArray 以减少使用 forEach 循环的重复性。 But it seems like a forEach loop can only take in one array at a time.但似乎 forEach 循环一次只能接收一个数组。 Any suggestions on how I can improve this?关于如何改进这一点的任何建议?

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++;
    }
});}

You should try index from forEach loop.您应该尝试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 you want to show the same message you can try this out.如果你想显示相同的消息,你可以试试这个。 or else you can use if/else statement for checking both the minArray and maxArray否则你可以使用 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