There are four ways to write for in JS?

This article has participated in the "Newcomer Creation Ceremony" event to start the road of gold creation together.

Introductory tutorial, please criticize and correct.

1. Traditional for loop

for (init; cond; inc) {
  // body
}
复制代码

Similar to C++ or Java, forthe loop setting is described with parentheses after the keyword, and ;the loop setting is separated into three parts by two semicolons in the parentheses, which are:

  1. initAn initialization statement (instruction), executed before the start of the entire loop
  2. condCondition (logical expression) that represents the condition under which the loop continues
  3. incAn auto-increment statement (instruction), executed after each loop body ends

The execution steps of the whole cycle are:

  1. execute initstatement
  2. Evaluate the condexpression and exit the loop if false
  3. execute loop bodybody
  4. Execute the incstatement, then return to step 2

E.g:

let sum = 0
for (let i = 1; i <= 10; i++) {
  sum += i
}
console.log(sum) // 55
复制代码

2. for of loop

for (const v of iterable) {
  // body
}
复制代码

This iterablerefers to various JS objects that can be iterated over. The most common examples are the array Array and the string String, in addition to arguments, NodeList, Map, Set and so on. The effect of execution is that the for loop will traverse iterableeach item, and in each loop, the representative variable vis the item of the current loop.

E.g:

const arr = [1, 2, 3, 4, 5]
let sum = 0
for (const v of arr) {
  sum += v
}
console.log(sum) // 15
复制代码

Advanced: for await (const v of iterable)Can be used for asynchronous loop traversal.

3. for in loop

for (const k in object) {
  // body
}
复制代码

The for in loop will traverse objecteach attribute. In each loop, the representative variable is the attribute name (key)k of the current attribute .

E.g:

const obj = { a: 1, b: 2, c: 3 }
let sum = 0
for (const k in obj) {
  sum += obj[k] // read the value from key
}
console.log(sum) // 6
复制代码

Pay special attention to the difference between for of and for in. The representative variable of the former is the value of the item (value), and the representative variable of the latter is the name of the attribute (key).

4. forEach method

Array.forEach(Function)
复制代码

forEach是JS数组的原生方法。它接受一个函数作为参数,执行效果是对数组的每一个项目,执行传入的函数。传入的函数可以接受三个参数:(element, index, array),其中element表示当前项目的值,index表示当前项目的下标,array表示循环的数组本身。

例如:

const arr = [1, 2, 3, 4, 5]
let sum = 0
arr.forEach(element => sum += element)
console.log(sum) // 15
复制代码

通常在程序中我们更倾向于使用for of循环来代替forEach方法,因为for关键字使得代码的可读性更高。但是在一些特殊的情况下,我们依然会使用forEach方法循环遍历数组中的每个项目。

高级:forEach可以传入异步函数,等效于使用for await (const v of Array)

Guess you like

Origin juejin.im/post/7080325478589923358