Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Found that JS loop has a lot of, if let say, feel some will not remember, this time to comb through the JS loop statement.

Let’s look at the basic two loops, the for loop and the while loop

The for loop

Let’s take a look at the code, as follows:

let arr = [111.444.888]
for(let i = 0; i < arr.length; i++){
    console.log(arr[i]) 
}
Copy the code

Here’s an example of a common for loop:

  1. Execute let I = 0

  2. Check whether I is less than arr. Length; If true, the loop ends. If false, the statement in the loop body is executed

  3. After executing the body statement, execute i++

  4. Repeat the above two steps until the cycle ends

A normal for loop iterates through the variable I to get the array members with the corresponding indices

The while loop

The while loop repeats when the result of the expression in () is converted to Boolean. When the value is true, the code in {} is executed. When the value is false, the while loop ends

let i = 1;
while (i < arr.length) {
    console.log(arr[i]);
    i++;
}
Copy the code

Here’s an example of a normal while loop:

  1. A variable I is declared before the while loop
  2. In a while loop, it points first(a)The result of the expression inbooleanValue, that is, I <arr.length, executed when the value is true{}The contents of the code inside
  3. when{}When the code inside is done, continue to execute(a)See the result of the expression inbooleanIf the value is true, the execution continues{}The code inside, repeating itself
  4. until(a)If the expression in is false, the loop ends

The end of the

So that’s how these two cycles work