What error in my JS code (repeat loops) is not correct and is lost when the user type 31

Asked

Viewed 32 times

-1

<script>

            // ver porquê será que se o usuário digitar 31 ele não apresenta nada 
            // só dá a mensagem após o 32

    
        for ( var i = window.prompt(`digite um valor entre 0 e 30: `) ; i <= 30 ; i++) {

            document.write(`Lista de números até o 30 :  ${i} <br>`)



                 } if (i >= 31) {
                    
                    document.write(`numero digitado ${i} acima de 30`)

            }


</script>
  • 2

    i is getting a string and not number. Do the type conversion.

  • 1

    The for always test the condition before executing the block. That is, if you type 31, the condition i <= 30 is fake and it comes out of the for (no longer performs what is inside it)

1 answer

0


you mixed a for with if in a weird way. Separate things let your Cod more levigel.

    <script>
    
    while(true){
        var i = window.prompt('digite um valor entre 0 e 30: ');
        if(i<=30){
            document.write('Lista de números até o 30 :  '+i+' <br>');
        } else {
            document.write('numero digitado '+i+' acima de 30');
            break;
        }
    
}   
    
    </script>

only this way it will only stop the while when some number larger than 30 is entered. so it will only display on the screen when this happens.

follow the fiddle link https://jsfiddle.net/dkc3vfxL/

following update:

var maxValue=30;
var i = window.prompt('digite um valor entre 0 e 30: ');
if(i<=maxValue){
    document.write('Lista de números até o 30 : ');
    for(u=i;u<=maxValue;u++){
       document.write(''+u+' ');
    }
} else {
    document.write('numero digitado '+i+' acima de 30');
}

  • the goal of the program is that if the user type for example 27 the system will list on screen 27,28,29,30 more wanted to let the possibility of the user type 31 and hence the system say that 31 is greater than 30 and therefore not valid

  • I’ll post the update

  • great help , thanks

  • if resolved flaga as solved ^^

  • I really appreciate the help

  • as I mark as solved friend ?

  • if helped have a arrow up you click on it and if you decided you mark the symbol check or side of the post.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.