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

How to deploy nextcloud network disk using docker

NextCloud You can share any files or folders on y...

Specific usage of CSS compound selectors

Intersection Selector The intersection selector i...

Implementation of Docker batch container orchestration

Introduction Dockerfile build run is a manual ope...

Incomplete solution for using input type=text value=str

I encountered a very strange problem today. Look a...

The difference between Div and table in HTML (discussed in detail in all aspects)

1: Differences in speed and loading methods The di...

How to install and deploy ftp image server in linux

Refer to the tutorial on setting up FTP server in...

Start a local Kubernetes environment using kind and Docker

introduce Have you ever spent a whole day trying ...

Analysis of the reasons why Vue3 uses Proxy to implement data monitoring

Vue data two-way binding principle, but this meth...

Vue components dynamic components detailed explanation

Table of contents Summarize Summarize When the ar...

How to implement email alert in zabbix

Implemented according to the online tutorial. zab...

Methods and steps to build nginx file server based on docker

1. Create a new configuration file docker_nginx.c...

Docker automated build Automated Build implementation process diagram

Automated build means using Docker Hub to connect...

JavaScript uses promise to handle multiple repeated requests

1. Why write this article? You must have read a l...