- JS全书:JavaScript Web前端开发指南
- 高鹏
- 1016字
- 2021-04-03 23:59:38
3.7 循环语句
循环语句可以让一部分代码反复执行,是一种常见的控制语句。
3.7.1 for
for语句是编程中常用的循环语句。
语法:
for ([initialization]; [condition]; [final-expression]){ statement }
for循环包含3部分——初始化、测试条件、表达式,可以在initialization中初始化变量,for循环会在每次迭代之前,先测试条件condition的值,如果值为true,则执行循环体内的代码,并执行final-expression,如果返回值为false,则不执行循环内的代码,也不会执行finalexpression。
示例代码:

3.7.2 while
语法:
while (condition) { statement }
while语句和for语句类似,同样是先测试条件condition(condition为必需参数),如果值为true,则执行循环内的代码。
示例代码:

· do…while
do…while和while类似,不同之处在于,不同于while的先测试再执行,do…while语句会先执行循环体内的代码,再测试条件,如果测试条件为true,则继续执行循环体内的代码。
语法:
do{ statement } while( condition )
示例代码:

乍看,上面的代码与while语句的输出结果相同,观察下面的示例能让我们更好地理解do…while和while的区别。

上述代码中,do…while和while的测试条件均为false,但do…while语句中循环体内的代码执行了一次,while语句中循环体内的代码没有执行,这也意味着do…while语句中循环体内的代码至少会执行一次。
3.7.3 for…in
for…in语句用来遍历对象的可枚举的属性,关于对象属性是否可枚举,会在后续章节中讲到,这里不必理会。
语法:
for (prop in object ){ statement }
示例代码:

不要对数组使用for…in语句,因为在遍历数组时,prop表示的是索引,但这个索引是一个字符串,示例如下。

这就导致我们在用索引做运算时,可能出现意外的问题(尽管可以使用类型转换来处理,但不推荐)。
再看下面的示例。

上述代码中,for…in语句将数组原型上的方法也进行了输出,这与我们期望的结果不同。假如代码中包含了其他对数组原型进行了修改的代码,for…in语句在遍历数组时就可能出现问题,所以,千万不要对数组使用for…in语句。
3.7.4 for…of
for…of语句在可迭代对象(包括Array、Map、Set、String、arguments、NodeList对象等)上创建一个迭代循环,对每个不同属性的属性值调用一个自定义的有执行语句的迭代挂钩。
语法:
for (variable of iterable) { statements }
示例代码:

3.7.5 break和continue语句
break和continue用于控制循环,在上一节的条件语句中,我们接触了break,break用于跳出当前循环,continue则是跳出当次循环,上述的循环语句都支持break和continue。
对比以下代码可以看出两者的区别。

上述代码中,在i等于3时,break语句跳出for循环,不再继续往下执行,因此程序只输出0、1、2;而continue语句只是跳出当次循环,因此程序不输出3,循环继续,最终输出0、1、2、4。
练习
- 使用不同的循环语句输出0~10。
- 使用不同的循环语句输出0~10,并使用break。
- 使用不同的循环语句输出0~10,并使用continue。