Get the App
SLTechnology News&Howtos  ›  Development  › 

How to write JavaScript loop

Shulou Source: shulou.com Published: 2022-06-02 23:36:36 09月11日 Update

This article mainly introduces how to write the JavaScript cycle, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

JavaScript loops are written in the following ways: 1, "for (let index = 0; index < len; index++) {...}", 2, "myArray.forEach (function (index) {...}", and so on.

Several Writing methods of for cycle of javascript

Background

The for loop in javascript has a variety of choices, but do you know what the difference is? When and which cycle is the best strategy? The above are what this article would like to discuss, welcome to communicate.

Description

1. For cycle 20 years ago

/ / 20 years ago, it was written as let len = myArray.Lengthfor (let index = 0; index < len; index++) {console.log (myArray)}

Keep to the rules.

2 、 forEach

/ / ES5 is written in myArray.forEach (function (index) {/ / manipulate your index,index is the element in the array})

Disadvantages, no return value.

3 、 for...in

/ / the way ES5 is written, I advise you to be careful about for (let index in myArray) {/ / do not do this console.log (myArray [index]);}

The worst thing to do is because the index at this time is a string and is not necessarily output in the order of the array, which is scary.

Applies only to key that traverses ordinary objects.

4 、 for...of

/ * * ES6 writing * supports array * class array objects (such as NodeList objects) * string * Map*set*/for (let value of myArray) {console.log (value);} Thank you for reading this article carefully. I hope the article "how to write the JavaScript cycle" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Loops writings arrays articles objects characters strings years ago ways support ordinary bad well-behaved values practices elements interests and at the same time a variety of Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Tech Info Microsoft Shulou Technology MySQL