Differences and usage examples of for, for...in, for...of and forEach in JS

Differences and usage examples of for, for...in, for...of and forEach in JS

for loop

Basic syntax format:

for(initialize variable; conditional expression; operation expression){

Loop body statement;
}

The normal for loop can be used in both Array and Object. In a for loop, you can use return, break, etc. to interrupt the loop.

//Traverse the array var arr = [1,2,3,4,5];
        for(var i=0;i<arr.length;i++){
            console.log(arr[i]);
        }
//Traverse the object var obj={
            x0:10,
            x1:20,
            x2:30
        }
        for(var k=0;k<3;k++){
            console.log(obj['x'+k]);
        }

When traversing objects, there are obviously significant restrictions on the naming of attributes and the value of k.

forEach loop

Basic syntax format:

arr.forEach(function(k){
console.log(k);
})

Take the elements from the array one by one and put them in k, then pass k as a parameter to the function

.forEach() is a method of the Array prototype that allows you to iterate over the elements of an array. .forEach() cannot iterate over objects. The forEach method cannot use the break statement to jump out of the loop, or use return to return from the function body.

//Traverse the array var arr = [3,2,3,9,5];
         arr.forEach(function(value,arr){
            console.log(value);
         })

for…in loop

Basic syntax format:

for(var variable in array name or collection name)
{
Array name [variable]
}

The index into the array or collection stored in the variable.

 //Traverse the array var arr = [1,2,3,4,5];
        for(var i in arr){
            console.log(arr[i]);
        }
//Traverse the object var obj={
            x0:10,
            x1:20,
            x2:30
        }
        for(var k in obj){
            console.log(obj[k]);
        }

1. The subscript value may be a string type

2. The loop will not only traverse the array elements, but also any other custom attributes added. For example, if obj contains a custom attribute, obj.name, then this name attribute will also appear in this loop.

3. In some cases, the above code will loop the array in random order

When the for-in loop was first designed, it was used for objects with string values ​​as keys. rather than an array.

for…of loop

Basic syntax format:

for(var variable of array name or collection name)
{
console.log(variable);
}

Variables store elements in arrays or collections.

 //Traverse the array var arr = [3,2,3,9,5];
         for(var value of arr){
            console.log(value);
         }
//Traverse the object var obj={
            x0:10,
            x1:20,
            x2:30
        }
        for(var k of Object.entries(obj)){
            console.log(k);
        }

The entries() method returns an array iterator object that contains the array's key/value pairs.

The index value of the array in the iteration object is used as the key and the array element is used as the value.

1. You can avoid all for-in loop pitfalls

2. Unlike forEach(), you can use break, continue and return

3.The for-of loop supports more than just array traversal. The same applies to many array-like objects.

4. It also supports string traversal

5. for-of is not suitable for processing original native objects

Summarize

1.'for...in' is used to iterate over all 'enumerable' properties of an object, including inherited enumerable properties. This iteration statement can be used for array strings or ordinary objects, but not for Map or Set objects.

2. 'for...of' is used for 'iterable' objects, iterating over their values ​​rather than their properties. This iteration statement can be used with array, string, Map or Set objects, but not with ordinary objects.

This is the end of this article about the differences and usages of for, for...in, for...of and forEach in JS. For more information about the differences between for, for...in, for...of and forEach in JS, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Usage and difference analysis of JS forEach and map methods
  • The difference between forEach and for in js

<<:  Docker runs operations with specified memory

>>:  On Visual Design and Interaction Design

Recommend

Use CSS content attr to achieve mouse hover prompt (tooltip) effect

Why do we achieve this effect? ​​In fact, this ef...

How to safely shut down a MySQL instance

This article analyzes the process of shutting dow...

The difference between MySQL count(1), count(*), and count(field)

Table of contents 1. First look at COUNT 2. The d...

HTML insert image example (html add image)

Inserting images into HTML requires HTML tags to ...

Solution to incomplete text display in el-tree

Table of contents Method 1: The simplest way to s...

Several things to note when making a web page

--Homepage backup 1.txt text 2. Scan the image 3. ...

Founder font library Chinese and English file name comparison table

Founder Type Library is a font library developed ...

Vue dynamic menu, dynamic route loading and refresh pitfalls

Table of contents need: Ideas: lesson: Share the ...

Summary of knowledge points about null in MySQL database

In the MySQL database, null is a common situation...

Solution to the conflict between nginx and backend port

question: When developing the Alice management sy...

CentOS 7 installation and configuration tutorial under VMware10

If Ubuntu is the most popular Linux operating sys...

A brief discussion on docker-compose network settings

Networks usage tutorial Official website docker-c...

Introduction to TypeScript interfaces

Table of contents 1. Interface definition 2. Attr...

How to hide elements on the Web and their advantages and disadvantages

Example source code: https://codepen.io/shadeed/p...