This series experience video tutorial => click to watch: Bilibili

The while loop

The while statement consists of a loop condition and a block of code that executes over and over again as long as the condition is true.

var n = 1

while (n <= 10) {
  console.log(n);
  n++ // Without this statement, the while condition will always be true, causing an infinite loop
}
Copy the code

do… The while loop

do… A while loop is similar to a while loop, except that the body of the loop is run once and then the condition is judged.

var m = 1
do {
  console.log(m);
  m++
}while(m <= 10);
Copy the code

Whether the condition is true or not, do… The while loop runs at least once, which is the biggest feature of this structure. Also, do not omit the semicolon after the while statement.

breakStatements andcontinuestatements

Both the break statement and the continue statement jump, allowing code to execute out of the existing order.

The break statement is used to break out of the loop.

var n = 1
while (n <= 10) {
  console.log(n);
  n++
  if (n == 6) break
}
Copy the code

The continue statement is used to break out of the loop

var n = 1
while (n <= 10) {
  console.log(n);
  n++
  if (n == 6) continue
}
Copy the code

practice

  • Take the sum of all even numbers up to 100
var n = 0
var sum = 0
while (n < 100) {
  n++
  if (n % 2! =0) continue
  sum = sum + n
}
console.log(sum);
Copy the code
  • Print right triangles
*
**
***
****
*****
******

var i = 1
var str = ' '
while (i <= 3) {
  var j = 1
  while (j <= i) {
    str += The '*'
    j++
  }
  str += '\n'
  i++
}
console.log(str);
Copy the code

homework

  • Console prints isosceles triangles, and can adjust the number of triangle layers by variable
     *
    ***
   *****
  *******
 *********
***********

var n = 6 / / layer
var str = ' ' // The final concatenated triangle string.console.log(str);
Copy the code