Home  >  Article  >  Web Front-end  >  What are the ways to write JavaScript loops?

What are the ways to write JavaScript loops?

藏色散人
藏色散人Original
2021-10-26 14:57:052468browse

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])
}

was quite satisfactory.

2. forEach

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

Disadvantage: no return value.

3. for...in

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

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);
}

[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!

Statement:
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