Javascript Loop 循環 7種方法

  1. 7 Methods to Loop In JavaScript
    1. 01 For Loop
    2. 02 While Loop
    3. 03 Do-While Loop
    4. 04 For-Of Loop
    5. 05 For-In Loop
    6. 06 Map Loop
    7. 07 For-Each Loop

7 Methods to Loop In JavaScript

01 For Loop

The most simple and basic loop. Very straightforward to use.

// for loop
const numbers = [22,34,46,58];

for (let i = 0; i < numbers.length; i++){
    console.log(numbers[i]*2);
}

02 While Loop

It’s similar to for loop in terms of complexity and also very straightforward to use.

// while loop
const numbers = [22,34,46,58];
let i = 0;

while (i < numbers.length){
    console.log(numbers[i]*2);
    i++;
}

03 Do-While Loop

The syntax look similar to while loopbut the only difference is the code is executed one time before checking the condition.

// Do-While Loop
const numbers = [22,34,46,58];
let i = 0 ;
do{
    console.log(numbers[i]*2);
    i++;
}while(i < numbers.length);

04 For-Of Loop

A loop that can be used for arrays to iterate over them without specifying the last limit. This loop ends when reach the last index of the array.

// For-Of Loop
const numbers = [22,34,46,58];

for(const num of numbers){
    console.log(num*2);
}

05 For-In Loop

Similar to for-of loop but it’s used on JavaScript objects.

// For-In-Loop
const numbers = {
    1:22,
    2:34,
    3:46,
    4:58
};

for(const num in numbers){
    console.log(numbers[num]*2);
}

06 Map Loop

An ES6 approach to iterate over an array and store the result in a new variable.

// Map Loop
const numbers = [22,34,46,58];
const doubleofNumbers = numbers.map(num => {
    return num*2;
});

console.log(doubleofNumbers);

//result:# [ 44, 68, 92, 116 ]

07 For-Each Loop

Also an ES6 approach and similar to the “map” but it only iterates over an array without making any changes oro returning any values.

This means you can’t tweak the array but you can use the individual indexes’ values.

//For-Each Loop
const numbers = [22,34,46,58];
numbers.forEach(num => {
    console.log(num*2);
});

//result:# 44 68 92 116

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件至 kimfei2014@gmail.com
github