简体   繁体   中英

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(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. But it seems like a forEach loop can only take in one array at a time. 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.

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

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
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM