I have been testing some things in JavaScript
and, since I am learning, in practice I have encountered an error executing a cycle while()
that I describe next.
What I need is to make a prompt()
that asks for a password to the user to enter it, such as "Miguel", and to return a "welcome" message (Part resolved). Now, I also need to have a limited number of attempts and when I overstep this one I get an "error" message.
I have solved everything with a cycle while()
that contains the conditions that I will leave in the example of the code, but the problem is that when executing the condition where it counts the number of attempts ( intento++
) until fulfilling the maximum of attempts allowed and the code closes the execution ( break;
), therefore does not restart me or continues with the cycle, this means that it does not rerun the prompt()
and also reaches the maximum number of attempts without executing all the cycle again.
The idea is to run it in such a way that if I enter an "incorrect" password, add the value of intento
once every time the cycle restarts (rerunning from the prompt's appearance until the end), so that if we re-enter the password again this attempt is added again to intento
, which does not happen since intento++
is executed until it reaches three and the program has to close to reach the maximum number of attempts, without that the user has entered anything.
var pass = prompt("Introduzca la contraseña");
var intento = 0;
while (pass != undefined) {
if (intento < 3) {
if (pass == "Miguel") {
alert("Bienvenido Miguel.");
break;
} else if (pass != "Miguel") {
intento++;
alert("Introduzca una clave valida.");
continue;
}
} else {
alert("Ha intentado demasiadas veces.");
break;
}
}