[英]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.