Summary of the use of three for loop statements in JavaScript (for, for...in, for...of)

Summary of the use of three for loop statements in JavaScript (for, for...in, for...of)

Preface

Every developer who comes into contact with JS will inevitably deal with the for loop. After all, it is one of the essential tools for traversal. I believe everyone is getting tired of the for loop statement in JavaScript. There are many articles talking about how to reduce the for loop statements in the code, but you have to admit that they are really useful. Today, I will summarize three for loop statements in front-end JavaScript.

for

This is probably the most widely used loop statement. It is simple and practical, and its performance is still online most of the time. The only disadvantage is that it is too ordinary and has no characteristics, which makes many people unwilling to use it now.

const array = [4, 7, 9, 2, 6];
for (let index = 0; index < array.length; index++) {
    const element = array[index];
    console.log(element);
}
// 4, 7, 9, 2, 6

for...in

The for...in statement can iterate over an object's enumerable properties, except Symbol, in any order.

const temp = {name: "temp"};
function Apple() {
    this.color = 'red';
}

Apple.prototype = temp;

const obj = new Apple();

for (const prop in obj) {
    console.log(`obj.${ prop } = ${ obj[prop] }`);
}

// obj.color = red
// obj.name = temp

If you only care about the properties of the object itself, not its prototype, then use getOwnPropertyNames() or perform hasOwnProperty() to determine whether a property is a property of the object itself.

const temp = {name: "temp"};
function Apple() {
    this.color = 'red';
}

Apple.prototype = temp;

const obj = new Apple();

for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        console.log(`obj.${ prop } = ${ obj[prop] }`);
    }
}

// obj.color = red

Of course, it can also be used to traverse an array.

const arr = [1, 2, 3, 4, 5];
for (const key in arr) {
    console.log(key)
}
// 0,1,2,3,4

You can use for...in to traverse an array, but there are the following problems:

  1. index The index is a string number (note, not a number) and cannot be directly used for geometric operations.
  2. The traversal order may not be in the internal order of the actual array (it may be in random order).

Therefore, it is generally not recommended to use for...in to traverse an array.

for...of

The for...of statement creates an iteration loop over an iterable object (including Array, Map, Set, String, TypedArray, arguments object, etc.), calls the custom iteration hook, and executes statements for each different property value.

const array = ['a', 'b', 'c'];
for (const element of array) {
    console.log(element);
}

// a
// b
// c

The difference between for...of and for...in:

  • The for...in statement iterates over the enumerable properties of an object in arbitrary order.
  • The for...of statement iterates over the iterable object to define the data to be iterated.
Object.prototype.objCustom = function () { };
Array.prototype.arrCustom = function () { };

let iterable = [3, 5, 7];
iterable.foo = 'hello';

for (const key in iterable) {
    console.log(key); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
// 0, 1, 2, "foo", "arrCustom", "objCustom"

for (const key of iterable) {
    console.log(key);
}
// 3, 5, 7

Use for...of to traverse the Map structure:

let nodes = new Map();
nodes.set("node1", "t1")
    .set("node2", "t2")
    .set("node3", "t3");

for (const [node, content] of nodes) {
    console.log(node, content);
}
// node1 t1
// node2 t2
// node3 t3

It can be seen that it is quite convenient to use for...of to traverse the Map structure. It is recommended to use it!

Summarize

  1. If you are tired of using ordinary for loops, it is recommended to use for...of instead.
  2. All three types of loops can use the break keyword to terminate the loop, or use the continue keyword to skip the current loop.
  3. The for...of loop has the widest scope of applicability.

This concludes this article on the use of three for loop statements in JavaScript. For more information about for loop statements 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:
  • Differences and usage examples of for, for...in, for...of and forEach in JS
  • Analyzing the difference between JavaScript for in and for of through examples
  • Summary of examples of using forEach, for in, and for of loops in js
  • Detailed explanation of js traversal (forEach, map, for, for...in, for...of)
  • Detailed explanation of the usage of for...in and for...of in Js
  • A brief analysis of the usage of map, filter, some, every, forEach, for in, for of in JS
  • A comprehensive analysis of the loop methods in JavaScript: forEach, for-in, for-of
  • A detailed introduction to for/of, for/in in JavaScript

<<:  How to remove MySQL from Ubuntu and reinstall it

>>:  Solutions to black screen when installing Ubuntu (3 types)

Recommend

Q&A: Differences between XML and HTML

Q: I don’t know what is the difference between xml...

Python Flask WeChat applet login process and login api implementation code

1. Let’s take a look at the effect first Data ret...

Summary of seven MySQL JOIN types

Before we begin, we create two tables to demonstr...

VMWare Linux MySQL 5.7.13 installation and configuration tutorial

This article shares with you the tutorial of inst...

Ideas and methods for incremental backup of MySQL database

To perform incremental backup of the MySQL databa...

Solution to mysql server 5.5 connection failure

The solution to the problem that mysql cannot be ...

How to convert Chinese into UTF-8 in HTML

In HTML, the Chinese phrase “學好好學” can be express...

Let's talk about the Vue life cycle in detail

Table of contents Preface 1. Life cycle in Vue2 I...

Implementation of React virtual list

Table of contents 1. Background 2. What is a virt...

JS implements city list effect based on VUE component

This article example shares the specific code for...

Practical Optimization of MySQL Paging Limit

Preface When we use query statements, we often ne...

JS object copying (deep copy and shallow copy)

Table of contents 1. Shallow copy 1. Object.assig...

XHTML Getting Started Tutorial: Commonly Used XHTML Tags

<br />Just like an article, our web pages sh...