js - various for loop analysis

The three most used structures in our development are: sequential structure, selection structure and circular structure. There are various loop structures in JavaScript, such as the most common for loop, forEach loop, for... In loop and for... of loop; of course, there are other loops such as while, but this article only discusses various for loops and analyzes their advantages and limitations.

1. Normal for loop

The for loop is the most common and frequently used

let array = [3,5,2,1]
for (let i = 0; i < array.length; i++) {
    console.log(array[i]) // 3 5 2 1
}

I believe every developer has used it, so there is no need to explain it too much; It should be noted that there are three parts in the for bracket. The middle part is an expression that returns true or false to judge whether to continue executing the internal code. Don't be surprised if the following code appears

// The expression part is 1, so it is always true. It will be executed until i === 5
for (let i = 0; 1; i++) {
    console.log(i) // 0 1 2 3 4 5
    if (i === 5) break
}

Limitations: as the earliest loop structure, the for loop code is relatively redundant

2. forEach

forEach is specifically designed for array loops

let array = [3,5,2,1]
// item: current value, index: current value index
array.forEach((item, index) => {
    console.log(item); // 3 5 2 1
    console.log(index); // 0 1 2 3 
    if (item === 5) return
})

What's wrong with the above code? Yes, why does return not work after item === 5

Limitation: in forEach, return does not work, and break will report illegal statements

3. for...in

for... in is designed to traverse the object, and can traverse the key of the object; You can also traverse arrays, because arrays are strictly objects with special key names.

const obj = {
    name: 'lisi',
    age: 13,
}

for (const key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) {
        console.log(key) // name age
        console.log(obj[key]) //lisi 13
    }
}

If object is not judged hasOwnProperty. Call (obj, key) will get the attributes from the prototype at the same time

function Person(name, age) {
    this.name = name
    this.age = age
}

Person.prototype.friend = 'zs'

let p = new Person('lisi', 13)

for (const key in p) {
    console.log(p[key]) // lisi 13 zs
}

Use for... in to traverse the array

let arr = [3,5,2,1]
for (const key in arr) {
    console.log(typeof key) // string
    console.log(arr[key]) // 3 5 2 1
}

Limitations: for... in traversing the object will get the properties on the prototype; For... in: the index value of the traversal array is of type string; The order of traversing properties cannot be guaranteed

4. for...of

es6 adds a new loop structure to replace forEach and for... in. For... of is used to traverse iteratable data structures, such as arrays, strings, sets, and map maps.

let arr = [3,5,2,1]
for (const iterator of arr) {
    console.log(iterator) // 3 5 2 1
}

Ordinary objects cannot be iterated

let obj = {
    name: 'lisi',
    age: 13,
}
for (const iterator of obj) {
    console.log(iterator) // Obj is not iteratable
}

// Class array objects can be accessed through array From processing, while ordinary objects can only customize iterators
// Through the following custom iterator
obj[Symbol.iterator] = function () {
    // Gets an array of all keys for the current object
    var keys = Object.keys(this);
    var count = 0;
    return {
        next() {
            // If the current count is less than the length of the key array, the traversal has not been completed
            if (count < keys.length) {
                // Return value
                return { value: obj[keys[count++]], done: false };
            } else {
                return { value: undefined, done: true };
            }
        }
    }
};

for... Of cannot get the index of the traversal element. It must be used in an alternative way

let arr = [3,5,2,1]
// Structure assignment
for (const [index, iterator] of new Map(arr.map(( item, i ) => [i, item]))) {
    console.log(index) // 0 1 2 3
    console.log(iterator) // 3 5 2 1
}

Limitations: for... of cannot print index; For... of cannot traverse normal objects

Keywords: Javascript iterator

Added by zab329 on Fri, 24 Dec 2021 00:18:25 +0200