JS loop summary

Time:2020-11-24
const arr = [1, 2, 3];

//For loop: can use break, continue, return to control the loop; access elements indirectly through subscript
for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    console.log(element);
}

//Foreach: you can't use break and continue to control the loop (the function's original intention is to traverse each element), but you can use return. The effect is equivalent to continue (not recommended in this function)
arr.forEach((value, index) => {
    if (value == 2) {
        return false;
    }
    // console.log(value);
});

//For in: it is best used to traverse objects, support break and continue, and return to terminate the loop
for (const key in arr) {
    if (arr.hasOwnProperty(key)) {
        const element = arr[key];
        // if(element === 2){
            // break;
        // }
        console.log(element);
    }
}

//For of: a traversal method specially designed for arrays. It directly traverses its attributes, supports break and continue, and return terminates the loop
//You can also traverse the Symbol.iterator Any data structure of the interface
for (const item of arr) {
    if(item === 2){
        continue;
    }
    // console.log(item);
}

const iterator = arr[Symbol.iterator]();
while(true){
    const next = iterator.next();
    if(next.done){
        break;
    }
    // console.log(next.value);
}

//Every: array traversal in disguise
arr.every((value, index) => {
    // console.log(index, value);
    Return true; // return a true value to continue the next loop is equal to continue, and return a false value to end the loop is equivalent to break
});