js--循环
重复运行同一代码的方法。
while
语法:while(condition){ }
如果condition为真,执行代码块,否则跳出循环。
condition可以是比较,可以是表达式,也可以是变量,条件会被计算并转换为布尔值。
例如:
let num;
while (num) {
console.log('code')
}
// 代码块不执行
while (1 < 2) {
console.log('code')
}
// 'code' 'code' 'code' ...
如果循环体只有一条语句,则可以省略大括号 {…}
let i = 3
while (i) console.log(i--)
do while
语法:do{ }while(condition)
do while会首先执行代码块在判断条件,condition为真,执行循环体,否则跳出循环。
condition可以是比较,可以是表达式,也可以是变量,条件会被计算并转换为布尔值。
无论是否条件是否为真,do{ }while()至少执行一次。
do {
console.log('do while')
} while (false)
// do while
let num = 3
do {
num--
console.log(num)
} while (num > 0)
// 2 1 0
for
语法:for (begin; condition; step) { }
begin:一个表达式 (包含赋值语句) 或者变量声明。
condition:一个条件表达式被用于确定每一次循环是否能被执行。 step:每次循环的最后都要执行的表达式
首先执行begin,检查条件,为真,执行代码体,代码体执行完,执行step内容。否则结束。
begin只执行一次。
let num = 3
for (let index = 0; index < num; index++) {
console.log(index)
}
// 0 1 2
在使用let声明的变量只能在循环中可见
let num = 3
for (let index = 0; index < num; index++) {
console.log(index)
}
console.log(index) // Uncaught ReferenceError: index is not defined
三个表达式都可以可选的,但是;必须存在。
第二个表达式如果被忽略,那么就被认为永远为真
for (;; ) {
console.log('1') //无限循环
}
// 1 1 1 1 ...
跳出循环
循环中条件为假会结束循环,也可以强制结束
break
结束循环
let num = 10
for (let index = 0; index < num; index++) {
if (index === 3) {
break
}
console.log(index)
}
// 0 1 2
continue
跳出本次循环
let num = 6
for (let index = 0; index < num; index++) {
if (index === 3) {
continue
}
console.log(index)
}
// 0 1 2 4 5
break/continue标签
从一次从多层嵌套的循环中跳出来
语法:labelName: for (...) { ... }
break /continue 语句跳出循环至标签处:
break 跳出循环至标签处。
label: for (let index = 0; index < 4; index++) {
for (let i = 0; i < 4; i++) {
console.log(index + '===' + i)
if (i === 1) {
break label
}
}
}
console.log('hahha')
// 0===0 0===1 hahha
continue 执行跳转到标记循环的下一次迭代。
label: for (let index = 0; index < 3; index++) {
for (let i = 0; i < 3; i++) {
console.log(index + '===' + i)
if (i === 1) {
continue label
}
}
}
console.log('hahha')
//0===0 0===1 1===0 1===1 2===0 2===1 hahha
只有在循环内部才能调用
break/continue,并且标签必须位于指令上方的某个位置。