基础-循环与迭代
约 334 字大约 1 分钟
2025-10-09
JavaScript 中提供了这些循环语句:
- for 语句
- while 语句
- do...while 语句
- for...in 语句
- for...of 语句
- label 语句
- break 语句
- continue 语句
for
for ([初始表达式]; [条件表达式]; [增量表达式]) {
// 要执行的代码块
}while
while (条件表达式) {
// 要执行的代码块
}do...while
与 while 类似,但保证代码块至少执行一次,因为条件判断在循环之后。
do {
// 要执行的代码块
} while (条件表达式);for...in
用于遍历对象的可枚举属性(包括原型链上的)。主要用于对象,不推荐用于数组。
for (变量 in 对象) {
// 使用变量的代码
}示例:
const person = {
name: 'Alice',
age: 30,
city: 'New York'
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
// 输出: name: Alice, age: 30, city: New York
}for...of
用于遍历可迭代对象(Array, String, Map, Set, arguments等)的值。
for (变量 of 可迭代对象) {
// 使用变量的代码
}示例:
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color); // 输出: 'red', 'green', 'blue'
}循环中断
break:
- 直接结束本次循环
- 在嵌套循环中, break 只在它所在的循环生效
continue:
- 中断本次循环, 进入下一次循环
- 在嵌套循环中, continue 也只在它所在的循环生效
