Skip to content

循环

https://www.yuque.com/qinsjs/jsinfo/rcgffb

关键字

break 跳出循环

continue 是 break 的“轻量版”。
它不会停掉整个循环。而是停止当前这一次迭代,并强制启动新一轮循环(如果条件允许的话)。

for

js
for (begin; condition; step) {
  // ……循环体……
}

如果 condition 成立 → 运行 body → 运行 step

begin进入循环时执行一次。
condition在每次循环迭代之前检查,如果为 false,停止循环。
body循环体
step在每次循环体迭代后执行。

标签

示例:一次性跳出两个循环

js
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coords (${i},${j})`, "");

    // 如果是空字符串或被取消,则中断并跳出这两个循环。
    if (!input) break outer; // (*)
  }
}

for in

object 的 for...in key 的显示与否,取决于 object property descriptors 中的 enumerable

for...in 会显示 继承 属性,使用 obj.hasOwnProperty(key) 判断是否为自身属性。

for of

todo

while

js
while (condition) {
  // 代码
  // 所谓的“循环体”
}

当 condition 为 true 时,执行循环体的 code。

do...while

js
do {
  // 循环体
} while (condition);

先 执行循环体 在检查条件

condition 为 true 继续