This is the 9th day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021.

1. forEach

ForEach is used to iterate over groups of numbers. ForEach has the following characteristics:

  • Compared to theforLoop, more concise form
  • No return value
  • You can’t usebreak,continueTo control the cycle
  • If usereturnAnd it willSkip the current loop, straight to the next loop,It doesn’t jump out of the outer function

In forEach, using break or continue will result in an error:

const arr = [0.1.2.3.4.5];

arr.forEach((item, index) = > {
    if (index === 2) break; // SyntaxError: Illegal break statement
    console.log(item);
});
Copy the code
const arr = [0.1.2.3.4.5];

arr.forEach((item, index) = > {
    if (index === 2) continue; // SyntaxError: Illegal continue statement
    console.log(item);
});
Copy the code

When index===2, we want to jump out of the test function, but we just skip the current loop:

const arr = [0.1.2.3.4.5];

function test() {
    arr.forEach((item, index) = > {
        if (index === 2) return;
        console.log(item);
    });
}

test();
/ / 0
/ / 1
/ / 3
/ / 4
/ / 5
Copy the code

Using the for loop, you can jump out of the test function:

const arr = [0.1.2.3.4.5];

function test() {
    const len = arr.length;
    for (let i = 0; i < len; i++) {
        if (i === 2) return;
        console.log(arr[i]);
    }
}

test();
/ / 0
/ / 1
Copy the code

2. for-in

for… The IN statement iterates through the enumerable properties of an object except Symbol in any order.

for (variable in object){
	...
}
Copy the code
  • variable: At each iteration,variableWill be assigned different valueskey, i.e.,The property name.
  • object:SymbolThe type ofCan be enumeratedThe object whose property is iterated over.

for … In is better for iterating over objects and is not recommended with arrays because the iterating order may not be in the index order of the actual array.

for … In iterates through all enumerable attributes, including stereotypes:

const obj = { a: 1.b: 2.c: 3 };

function myObj() {
    this.name = 'Jack';
}

myObj.prototype = obj;

const user = new myObj();

for (const prop in user) {
    console.log(`user.${prop} = ${user[prop]}`);
}
// user.name = Jack
// user.a = 1
// user.b = 2
// user.c = 3
Copy the code

If you want to iterate only over its own properties, you need to use the hasOwnProperty() method to determine if an attribute is an instance attribute of the object:

const obj = { a: 1.b: 2.c: 3 };

function myObj() {
    this.name = 'Jack';
}

myObj.prototype = obj;

const user = new myObj();

for (const prop in user) {
    if (user.hasOwnProperty(prop)) {
        console.log(`user.${prop} = ${user[prop]}`); }}// user.name = Jack
Copy the code

3. for-of

for… The of statement creates an iteration loop over iterable objects (including Array, Map, Set, String, TypedArray, Arguments objects, etc.) and executes the statement for the value of each different property.

for (variable of iterable) {
	...
}
Copy the code
  • variable: In each iteration, the attributes of thevalueAssigned tovariable.
  • 可迭代: An object whose properties are iteratively enumerated.

Unlike forEach(), it responds correctly to break, continue, and return statements.

Iterating arrays:

const arr = [10.20.30];

for (const value of arr) {
    console.log(value);
}
/ / 10
/ / 20
/ / 30
Copy the code

Iterative Map:

const map = new Map([['a'.1],
    ['b'.2],
    ['c'.3]]);for (const entry of map) {
    console.log(entry);
}
// ["a", 1]
// ["b", 2]
// ["c", 3]

for (const [key, value] of map) {
    console.log(value);
}
/ / 1
/ / 2
/ / 3
Copy the code

Iterating arguments objects:

(function () {
    for (const argument of arguments) {
        console.log(argument);
    }
})(1.2.3);

/ / 1
/ / 2
/ / 3
Copy the code

4. To summarize

  • forEachIs an array of methods, traversing the number of groups, no return value, cannot be usedbreak,continueAnd don’t usereturnTo get out of the outer function.
  • for... inStatement toAny orderIterated objectkey, includingThe prototype. It is not recommended toAn array ofUse together.
  • for... ofStatements traversaliterablethevalue.