There is an "else while"

9

Is there any way for me to do this? While it's one thing to do that, then when is it another to do that?

For example:

var i = 0; 
while(i < 5){
   //faça isso
   i++;
} else {
   //faça aquilo
}

Is it possible to do this somehow?

    
asked by anonymous 15.01.2018 / 12:15

2 answers

14

In JS does not exist, you need to create a flag within the loop for a if to be executed or not after the end of this loop. Or think of a different stream that does not need it.

In Python there .

The example question is not good because it does not need this algorithm. In fact this can be solved with a simple for . If the condition's data were unknown it could do something like this:

var entrada = 1; //teria que ser uma valor desconhecido
var entrou = false;
while (entrada < 10) {
    entrou = true;
    //faz algo mais aqui, caso contrário não teria sentido
    entrada++;
}
if (!entrou) {
    console.log("deu problema");
}
console.log("vamos tentar de novo");
var entrada = 11; //teria que ser uma valor desconhecido
var entrou = false;
while (entrada < 10) {
    entrou = true;
    //faz algo mais aqui, caso contrário não teria sentido
    entrada++;
}
if (!entrou) {
    console.log("deu problema");
}

Watch out for solutions that use the condition itself to decide whether to run or not, or if you use an inverted condition after the loop. This tends to generate bugs with maintenance. This violates DRY . Even at the beginning it may generate a bug and you do not realize it.

Depending on the condition you can call a function that has a side effect or causes a race condition and produces an unexpected result. You are likely to test and work. But one day something happens that does not work since it is not right. Work and be right not different things.

    
15.01.2018 / 12:22
-1

As you wrote the code there is else in javascript.

I suggest rewriting your code in another way, for example:

 while(i < 5){
   //faça alguma coisa
 }

 if(i >= 5){
   //faça outra couisa
 }

I do not know if this is the action that should be taken. If it does not tell us better what you want the code to do.

    
15.01.2018 / 14:19