Home > Web Front-end > Front-end Q&A > What are the ways to write JavaScript loops?

What are the ways to write JavaScript loops?

藏色散人
Release: 2021-10-26 14:57:05
Original
2543 people have browsed it

The ways to write JavaScript loops are: 1. "for (let index = 0; index < len; index ) {...}"; 2. "myArray.forEach(function(index){. ..}" method and so on.

What are the ways to write JavaScript loops?

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

What are the ways to write loops in JavaScript?

How to write for loops in javascript

Background

There are many options for for loops in javascript , but do you know what the difference is? When and which cycle should be used is the best strategy? The above are what this article wants to discuss, welcome to exchange.

Instructions

1. The for loop 20 years ago

//20年前的写法
let len = myArray.Length
for (let index = 0; index < len; index++) {
  console.log(myArray[index])
}
Copy after login

was quite satisfactory.

2. forEach

//ES5的写法
myArray.forEach(function(index){
    //操作你的index,index即为数组中的元素
})
Copy after login

Disadvantage: no return value.

3. for...in

//ES5的写法,劝你慎重
for (let index in myArray) { 
  // 千万别这样做
  console.log(myArray[index]);
}
Copy after login

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

Only suitable for traversal The key of an ordinary object.

4, for...of

/**ES6写法
*支持数组
*类数组对象(如:NodeList对象)
*字符串
*Map
*set
*/
for (let value of myArray) {
  console.log(value);
}
Copy after login

[Recommended learning: javascript basic tutorial]

The above is the detailed content of What are the ways to write JavaScript loops?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template