JavaScript提供了许多通过LOOPS迭代的方法。本教程解释了现代JAVASCRIPT中各种各样的循环可能性

目录:

  • for
  • forEach
  • do...while
  • while
  • for...in
  • for...of
  • for...in vs for...of

介绍

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 迭代属性名称

原文地址:https://segmentfault.com/a/1190000016110909

最新文章

  1. Excel VBA 函数
  2. Python笔记-集合,拷贝
  3. 小梅哥FPGA数字逻辑设计教程——基于线性序列机的TLC5620型DAC驱动设计
  4. 一些sql语句的常用总结(重要)
  5. 【SpringMVC】SpringMVC系列6之@CookieValue 映射请求Cookie 值
  6. 微软职位内部推荐-SDEII
  7. ZOJ 3941 Kpop Music Party 贪心
  8. Netty4.x中文教程系列(二) Hello World !
  9. 剑指OFFER之重建二叉树(九度OJ1385)
  10. JavaScript中模块“写法”
  11. 如何去掉List中的重复内容
  12. 删除句子UITableView额外的底线和切割线
  13. Tomcat剖析(四):Tomcat默认连接器(1)
  14. POJ 2553 The Bottom of a Graph (强连通分量)
  15. 匹配PC和移动端
  16. ibv_open_device()函数
  17. java 设计模式-缺省适配器模式
  18. Android进阶(十)Android 发邮件
  19. 【OpenGL】代码记录01创建窗口
  20. Python 死锁现象

热门文章

  1. HDFS 特殊权限位
  2. ora-01578
  3. kafka可视化工具安装及简单使用
  4. 【SQL】 java.sql.SQLException: You can't specify target table 'emp' for update in FROM clause
  5. Spring数据分析思维课
  6. k8s-helm01-----helm基本使用
  7. Linux终端中文显示乱码
  8. a lot of attention under the hood
  9. Hadoop、spark
  10. HTML <a> 标签的 href 属性_定位资源