本文共 1018 字,大约阅读时间需要 3 分钟。
The for...of
loop is my favorite way to loop in JavaScript.
for...of
循环是我最喜欢JavaScript循环方式。
It combines the conciseness of forEach
loops with the ability to break.
它结合了forEach
循环的简洁性和中断能力。
The syntax is this:
语法是这样的:
const list = ['a', 'b', 'c']for (const item of list) { console.log(item)}
You can break at any point in time using break
:
您可以使用break
随时break
:
const list = ['a', 'b', 'c']for (const item of list) { console.log(item) if (item === 'b') break}
You can skip an iteration using continue
:
您可以使用continue
跳过迭代:
const list = ['a', 'b', 'c']for (const item of list) { if (item === 'b') continue console.log(item)}
You can get the index of an iteration using entries()
:
您可以使用entries()
获取迭代的索引:
const list = ['a', 'b', 'c']for (const [index, value] of list.entries()) { console.log(index) //index console.log(value) //value}
Notice the use of const
. The for..of
loop creates a new scope in every iteration, so we can safely use that instead of let
.
注意const
的使用。 for..of
循环在每次迭代中都会创建一个新作用域,因此我们可以放心地使用它代替let
。
翻译自:
转载地址:http://oxmgb.baihongyu.com/