ZetCode

JavaScript while 关键字

最后修改于 2025 年 4 月 16 日

在本文中,我们将展示如何使用 while 关键字在 JavaScript 中创建循环。当指定的条件为真时,while 循环会执行一段代码块。

while 关键字

while 关键字创建一个循环,只要指定的条件计算结果为真,它就会执行一段代码块。每次迭代之前都会检查条件。如果条件变为假,循环将停止。

while 循环的基本语法是:while (条件) { ... }。条件可以是任何计算结果为布尔值的表达式。只要此条件保持为真,循环就会继续。

与 for 循环不同,while 循环没有内置的初始化或增量表达式。这些必须在循环之前和循环内手动处理。这使得 while 循环更加灵活,但需要仔细设置。

基本 while 循环

以下示例演示了 while 循环在 JavaScript 中的基本用法。

main.js
let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

此循环将计数器变量 i 初始化为 0。只要 i 小于 5,循环就会继续。在循环内,我们记录 i 的当前值,然后将其递增。循环运行 5 次。

$ node main.js
0
1
2
3
4

无限 while 循环

如果条件永远不会变为假,则 while 循环可能会变成无限循环。

main.js
let count = 0;
while (true) {
    console.log(count);
    count++;
    if (count > 3) {
        break;
    }
}

此示例显示了一个 while 循环,其条件始终为真。如果没有 break 语句,这将永远运行。我们使用计数器和 break 在 4 次迭代后退出。这种模式对于无限循环很有用。

$ node main.js
0
1
2
3

使用数组迭代的 while 循环

while 循环通常用于遍历数组。

main.js
const fruits = ['apple', 'banana', 'orange'];
let index = 0;

while (index < fruits.length) {
    console.log(fruits[index]);
    index++;
}

在这里,我们使用 while 循环遍历一个水果数组。我们初始化一个索引变量,并在每次迭代时递增它。循环继续进行,直到我们处理完所有数组元素。这类似于 for 循环,但带有手动索引管理。

$ node main.js
apple
banana
orange

使用用户输入的 while 循环

while 循环对于处理用户输入直到满足某个条件非常有用。

main.js
const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

let answer = '';

while (answer !== 'quit') {
    answer = readline.question('Enter a command (type "quit" to exit): ');
    console.log(`You entered: ${answer}`);
}

readline.close();

此示例使用 while 循环反复提示用户输入,直到他们输入“quit”。循环条件检查用户的输入。这种模式在命令行应用程序和交互式程序中很常见。

$ node main.js
Enter a command (type "quit" to exit): hello
You entered: hello
Enter a command (type "quit" to exit): quit
You entered: quit

具有复杂条件的 while 循环

while 循环条件可以是结合多个检查的复杂表达式。

main.js
let x = 0;
let y = 10;

while (x < 5 && y > 5) {
    console.log(`x: ${x}, y: ${y}`);
    x++;
    y--;
}

只要两个条件都为真,此循环就会继续:x 小于 5 并且 y 大于 5。循环每次迭代都会递增 x 并递减 y。当任一条件变为假时,循环停止。

$ node main.js
x: 0, y: 10
x: 1, y: 9
x: 2, y: 8
x: 3, y: 7
x: 4, y: 6

Do-while 循环

do...while 变体确保循环至少运行一次。

main.js
let num;
do {
    num = Math.floor(Math.random() * 10);
    console.log(`Generated: ${num}`);
} while (num !== 5);

此示例生成随机数,直到得到 5。与常规的 while 循环不同,do-while 循环始终至少执行一次。每次迭代后都会检查条件。当您需要在检查之前运行代码时,这很有用。

$ node main.js
Generated: 3
Generated: 7
Generated: 2
Generated: 5

实际用例:处理队列

这是一个使用 while 从队列中处理项目的实际示例。

main.js
const tasks = ['task1', 'task2', 'task3', 'task4'];

while (tasks.length > 0) {
    const currentTask = tasks.shift();
    console.log(`Processing: ${currentTask}`);
    // Simulate task processing
}

此代码处理来自队列的任务,直到所有任务完成。只要数组中有任务,while 循环就会继续。每次迭代都会删除并处理第一个任务。这种模式在作业处理系统中很常见。

$ node main.js
Processing: task1
Processing: task2
Processing: task3
Processing: task4

来源

while - 语言参考

在本文中,我们演示了如何使用 while 关键字在 JavaScript 中创建循环。While 循环用途广泛,适用于许多场景。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我已撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。