Home > Blockchain >  How do I skip a value using the while loop?
How do I skip a value using the while loop?

Time:07-11

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <head>LOOPS</head>
        <h1 id="string"></h1>
        <script language="javascript" type="text/javascript">
              let w = 10;
              while (w <= 15) {
                console.log(w);

                if (w == 12) {
                  continue;
                }
                w  ;
              }        
        </script>
    </body>
    </html>

This creates an infinite loop, But I'm trying to skip 12, if I remove the increment it doesn't display at all.

CodePudding user response:

You need to increase w value before you do the skipping, one method is to do it inside the while condition:

let w = 9;
while(  w<=15){

    if(w==12){
        continue;
    }
    console.log(w)
};

CodePudding user response:

The reason is that code:

let w = 10;
while (w <= 15) {
  console.log(w);
  if (w == 12) {
    continue;
  }
  w  ; // JS never access to this line after printing 10, 11 and 12
}

because continue statement jumps over one iteration in the loop. so JS never access to increment w variable, so it will infinite-loop just printing 12 and continue printing it without increment w; to solve it just increment it before you check if condition:

let w = 10;
while (w <= 15) {
  console.log(w);
  w  ;
  if (w == 12) {
    continue;
  }
}

  • Related