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, for
the 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:
init
An initialization statement (instruction), executed before the start of the entire loopcond
Condition (logical expression) that represents the condition under which the loop continuesinc
An auto-increment statement (instruction), executed after each loop body ends
The execution steps of the whole cycle are:
- execute
init
statement - Evaluate the
cond
expression and exit the loop if false - execute loop body
body
- Execute the
inc
statement, 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 iterable
refers 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 iterable
each item, and in each loop, the representative variable v
is 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 object
each 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)
。