JavaScript for..of循环

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

翻译自: https://flaviocopes.com/javascript-for-of-loop/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值