JavaScript的几种循环方式
2024-09-05 08:47:19
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
最新文章
- Excel VBA 函数
- Python笔记-集合,拷贝
- 小梅哥FPGA数字逻辑设计教程——基于线性序列机的TLC5620型DAC驱动设计
- 一些sql语句的常用总结(重要)
- 【SpringMVC】SpringMVC系列6之@CookieValue 映射请求Cookie 值
- 微软职位内部推荐-SDEII
- ZOJ 3941 Kpop Music Party 贪心
- Netty4.x中文教程系列(二) Hello World !
- 剑指OFFER之重建二叉树(九度OJ1385)
- JavaScript中模块“写法”
- 如何去掉List中的重复内容
- 删除句子UITableView额外的底线和切割线
- Tomcat剖析(四):Tomcat默认连接器(1)
- POJ 2553 The Bottom of a Graph (强连通分量)
- 匹配PC和移动端
- ibv_open_device()函数
- java 设计模式-缺省适配器模式
- Android进阶(十)Android 发邮件
- 【OpenGL】代码记录01创建窗口
- Python 死锁现象
热门文章
- HDFS 特殊权限位
- ora-01578
- kafka可视化工具安装及简单使用
- 【SQL】 java.sql.SQLException: You can&#39;t specify target table &#39;emp&#39; for update in FROM clause
- Spring数据分析思维课
- k8s-helm01-----helm基本使用
- Linux终端中文显示乱码
- a lot of attention under the hood
- Hadoop、spark
- HTML <;a>; 标签的 href 属性_定位资源