探讨JavaScript几种循环

介绍

JavaScript提供了许多迭代循环的方法。

for

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
  console.log(list[i]) //value
  console.log(i) //index
}
  • 您可以使用break中断for循环
  • 您可以使用continue继续for循环的下一次迭代

forEach

在ES5中引入。给定一个数组,您可以使用list.forEach()迭代其属性:

const list = ['a', 'b', 'c']
list.forEach((item, index) => {
  console.log(item) //value
  console.log(index) //index
})

//index is optional
list.forEach(item => console.log(item))
不过需要注意的是你无法摆脱这个循环。

do...while

const list = ['a', 'b', 'c']
let i = 0
do {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
} while (i < list.length)

您可以使用break中断while循环:

do {
  if (something) break
} while (true)

你可以使用continue跳转到下一个迭代:

do {
  if (something) continue

  //do something else
} while (true)

while

const list = ['a', 'b', 'c']
let i = 0
while (i < list.length) {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
}

您可以使用break中断while循环:

while (true) {
  if (something) break
}

你可以使用continue跳转到下一个迭代:

while (true) {
  if (something) continue

  //do something else
}

与do...while的区别在于do...while总是至少执行一次循环。

for...in

迭代对象的所有可枚举属性,给出属性名称。

for (let property in object) {
  console.log(property) //property name
  console.log(object[property]) //property value
}

for...of

ES2015引入了for循环,它结合了forEach的简洁性和破解能力:

//iterate over the value
for (const value of ['a', 'b', 'c']) {
  console.log(value) //value
}

//get the index as well, using `entries()`
for (const [index, value] of ['a', 'b', 'c'].entries()) {
  console.log(index) //index
  console.log(value) //value
}

注意使用const。此循环在每次迭代中创建一个新范围,因此我们可以安全地使用它而不是let。

for...in VS FOR...OF

与for...in的区别在于:

  • for...of 迭代属性值
  • for...in 迭代属性名称
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值