Use of forEach, for-in, and for-of loops in JavaScript

Source: Internet
Author: User
Tags foreach generator iterable new set prev

JavaScript has been born for more than 20 years. The method we have been using to loop an array is as follows:

For (var index = 0; index <myArray. length; index ++ ){
Console. log (myArray [index]);
}

Since JavaScript5, we can use the built-in forEach method:

MyArray. forEach (function (value ){
Console. log (value );
});

It is a lot easier to write, but it also has a short note: you cannot interrupt the loop (using a break statement or a return statement.

There is also a loop method in JavaScript: for-in.

The for-in loop is actually designed for loop "enumerable" objects:

Var obj = {a: 1, B: 2, c: 3 };
   
For (var prop in obj ){
Console. log ("obj." + prop + "=" + obj [prop]);
}

// Output:
// "Obj. a = 1"
// "Obj. B = 2"
// "Obj. c = 3"

You can also use it to loop through an array:

For (var index in myArray) {// This is not recommended
Console. log (myArray [index]);
}

We do not recommend that you use for-in to loop an array, because, unlike an object, the index of the array is different from the attribute of a common object and is an important numerical sequence indicator.

In short, for-in is a method used to loop objects with string keys.

For-of loop

JavaScript6 introduces a new loop method, which is a for-of loop. It is simpler than the traditional for loop and makes up for the short board of forEach and for-in loops.

Let's take a look at its for-of syntax:

For (var value of myArray ){
Console. log (value );
}

The syntax of for-of looks very similar to for-in, but it has many functions and can loop through many things.

For-of loop example:

Loop through an Array ):
Let iterable = [10, 20, 30];

For (let value of iterable ){
Console. log (value );
}
// 10
// 20
// 30
We can use const to replace let, so that it becomes an unchangeable static variable in the loop.

Let iterable = [10, 20, 30];

For (const value of iterable ){
Console. log (value );
}
// 10
// 20
// 30

Loop a string:

Let iterable = "boo ";

For (let value of iterable ){
Console. log (value );
}
// "B"
// "O"
// "O"
Loop through a typed array (TypedArray ):
Let iterable = new Uint8Array ([0x00, 0xff]);

For (let value of iterable ){
Console. log (value );
}
// 0
// 255

Loop through a Map:

Let iterable = new Map ([["a", 1], ["B", 2], ["c", 3]);

For (let [key, value] of iterable ){
Console. log (value );
}
// 1
// 2
// 3

For (let entry of iterable ){
Console. log (entry );
}
// [A, 1]
// [B, 2]
// [C, 3]

Loop through a Set:

Let iterable = new Set ([1, 1, 2, 2, 3, 3]);

For (let value of iterable ){
Console. log (value );
}
// 1
// 2
// 3

Loop a DOM collection

Loop a DOM collections, such as NodeList. We have discussed how to loop a NodeList before. Now we can directly use the for-of loop:

// Note: This will only work in platforms that have
// Implemented NodeList. prototype [Symbol. iterator]
Let articleParagraphs = document. querySelectorAll ("article> p ");

For (let paragraph of articleParagraphs ){
Paragraph. classList. add ("read ");
}

Loop an object with the enumerable attribute

The for-of loop cannot be directly used on common objects. However, if we loop through the attributes of an Object, we can use the built-in Object. keys () method:

For (var key of Object. keys (someObject )){
Console. log (key + ":" + someObject [key]);
}

Generators)
We can cycle a generator (generators ):

Function * maid () {// a generator function
Let [prev, curr] = [0, 1];
While (true ){
[Prev, curr] = [curr, prev + curr];
Yield curr;
  }
}

For (let n of fig ()){
Console. log (n );
// Truncate the sequence at 1000
If (n> = 1000 ){
Break;
  }
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.