JavaScript while 循环:语法、示例、无限循环解决方案与优化技巧

目次

1. 介绍

JavaScript 是网页开发中极其重要的编程语言。其特性之一,while 语句,是用于在条件满足时重复执行过程的基础结构。

本文将详细解释 JavaScript 的 while 语句——从基本用法到实用示例以及避免错误的技巧。本文面向初学者至中级学习者,采用清晰易懂的方式逐步演示真实代码示例。

1.1 本文目的

  • 了解基本语法: 学会如何使用 while 语句。
  • 实用示例: 学习在实际开发中有用的案例。
  • 避免常见错误: 学会防止诸如无限循环等典型错误。

1.2 为什么 while 语句重要?

循环是编程中使用最频繁的特性之一。while 语句在以下情形中特别有用:

  • 迭代次数未知: 验证用户输入或处理数据直至满足某个条件。
  • 动态处理: 控制实时数据处理系统或管理动画等场景。

在这些情境下,掌握 JavaScript 的 while 语句对于编写高效程序至关重要。

2. 什么是 while 语句?

JavaScript 的 while 语句 是一种循环结构,只要指定的条件求值为 true,就会重复执行过程。当条件变为 false 时,循环停止。

本节将说明 while 语句的基本语法以及其工作原理。

2.1 while 语句的基本语法

首先,来看一下 while 语句的基本语法。

语法:

while (condition) {
  // Code to run
}

各部分说明:

  1. 条件:
    * 指定循环继续的条件。只要该条件为 true,循环体内的代码就会执行。

  2. 要执行的代码:
    * 编写在条件满足时需要运行的代码块。

2.2 while 语句的基本示例

下面的示例按顺序打印 1 到 5 的数字。

代码示例:

let i = 1; // Set the initial value
while (i <= 5) { // Condition
  console.log(i); // Output the value
  i++; // Increment the counter
}

输出:

1
2
3
4
5

解释:

  1. 将变量 i 初始化为 1。
  2. 若条件 i <= 5 为 true,循环继续执行。
  3. console.log(i) 打印当前的 i 值。
  4. i++ 每次将 i 增加 1,直至条件变为 false 时循环结束。

2.3 while 语句的工作流程

while 循环的执行流程如下:

  1. 评估条件。
  2. 若条件为 true,执行循环体内的代码。
  3. 代码执行完毕后,再次评估条件。
  4. 当条件变为 false 时,退出循环。

如果将此流程可视化,大致如下:

1. Evaluate condition → true → run code → evaluate condition again
2. Evaluate condition → false → loop ends

2.4 注意:无限循环的风险

警告:
使用 while 语句时最需要留意的就是 无限循环

下面的示例中,条件始终为 true,导致循环永不停止。

无限循环示例:

let i = 1;
while (i <= 5) {
  console.log(i);
  // Infinite loop because i++ was forgotten
}

在这段代码里,i 的值从未改变,条件 i &lt;= 5 始终为 true,程序因此永不结束。

防止方法:
确保循环体内部会改变某些状态,使条件最终能够变为 false。

3. while 语句的基本用法

在本节中,我们将介绍使用 JavaScript while 语句 的具体示例,并解释如何处理不同的场景。我们会覆盖从基本模式到更实用的用例,让你能够轻松地在实际程序中应用它们。

3.1 示例:固定次数的重复

作为最基本的模式,让我们来看一个循环指定次数的例子。

代码示例:

let count = 1; // Initial value
while (count <= 5) { // Condition
  console.log(`Count: ${count}`); // Display the count
  count++; // Increment the counter
}

输出:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

关键要点:

  • 变量 count 在循环内部被更新,因此可以清晰地看到条件何时会变为 false。
  • 当你想要进行一定次数的简单重复时,这种方式非常理想。

3.2 示例:直到满足条件才停止

while 语句同样非常适合用于“直到满足特定条件”为止的重复。

示例:验证用户输入
该循环会一直弹出提示,直到用户输入一个有效的数字。

代码示例:

let input;
while (true) { // Start with a true condition
  input = prompt("Enter a number from 1 to 10:");
  if (input >= 1 && input <= 10) { // Exit if valid
    break;
  }
  alert("Invalid input. Please try again.");
}
console.log(`Entered number: ${input}`);

关键要点:

  • 循环条件一开始始终为 true,并在适当时机使用 break 退出。
  • 这种模式适用于用户输入检查和数据验证。

3.3 示例:按顺序处理数组元素

下面的示例演示如何访问并处理数组中的每个元素。

代码示例:

let fruits = ["Apple", "Banana", "Grape"];
let i = 0;
while (i < fruits.length) { // Use the array length as the condition
  console.log(`Fruit: ${fruits[i]}`);
  i++;
}

输出:

Fruit: Apple
Fruit: Banana
Fruit: Grape

关键要点:

  • 通过索引顺序处理数组元素。
  • 使用 i < fruits.length 可确保所有元素都被处理。

3.4 示例:持续处理直至条件为假

本例中,我们将一个数字不断除以二,直至它小于或等于 1。

代码示例:

let number = 100;
while (number > 1) { // Condition: number is greater than 1
  console.log(`Current value: ${number}`);
  number /= 2; // Halve the number
}

输出:

Current value: 100
Current value: 50
Current value: 25
Current value: 12.5
Current value: 6.25
Current value: 3.125
Current value: 1.5625

关键要点:

  • 循环会一直执行,直到条件变为 false。
  • 在循环内部递减或递增变量,可确保循环最终结束。

3.5 使用 break 和 continue

在 while 循环中,你可以使用 breakcontinue 来控制流程。

break:结束循环的示例

let i = 1;
while (i <= 10) {
  if (i === 5) break; // End the loop at 5
  console.log(i);
  i++;
}

输出:

1
2
3
4

continue:跳过特定条件的示例

let i = 0;
while (i < 10) {
  i++;
  if (i % 2 === 0) continue; // Skip even numbers
  console.log(i);
}

输出:

1
3
5
7
9

关键要点:

  • break: 完全退出循环。
  • continue: 跳过当前迭代,直接进入下一次循环。

3.6 小结

本节我们介绍了 JavaScript while 语句的基本使用模式和实用示例。

关键收获:

  • while 语句既适合固定次数的循环,也适合“直到满足条件”为止的循环。
  • 我们展示了处理数组元素和改变数值的实用案例。
  • 通过 breakcontinue,可以灵活地控制循环流程。

4. 无限循环及其避免方法

当使用 JavaScript 的 while 语句 时,需要特别注意 无限循环。当条件始终为真且过程永远重复时,就会出现无限循环。在本节中,我们将详细说明无限循环的成因以及如何防止它们。

4.1 什么是无限循环?

无限循环是指 循环永远不会停止,因为退出条件从未满足。它可能导致程序无响应,甚至使浏览器崩溃。

4.2 无限循环示例

示例 1:退出条件从未改变

let count = 1;
while (count < 5) {
  console.log(count);
  // Infinite loop because count is not updated
}

示例 2:条件始终为真

while (true) { // The condition is always true
  console.log("Running an infinite loop");
}

4.3 如何防止无限循环

编写代码时,请牢记以下要点,以避免无限循环。

1. 仔细设计条件

设计循环,使条件能够可靠地变为 false。

改进示例:

let count = 1;
while (count < 5) {
  console.log(count);
  count++; // Increase count so the condition changes
}

2. 明确写出退出条件

在代码中显式声明退出条件,便可安全结束循环。

使用 break 的示例:

let count = 1;
while (true) {
  console.log(count);
  if (count >= 5) { // Specify a clear exit condition
    break; // Exit the loop
  }
  count++;
}

3. 添加时间限制或尝试次数限制

除了条件检查之外,加入时间或尝试次数限制可以防止意外情况。

示例:带尝试次数限制的处理

let attempts = 0; // Attempt counter
while (attempts < 10) {
  if (Math.random() > 0.8) { // Exit if the condition is met
    console.log("Success!");
    break;
  }
  console.log("Retrying...");
  attempts++;
}

4.4 实际示例:验证用户输入

下面的示例会一直重复处理,直到用户输入有效值。

代码示例:

let input;
while (true) {
  input = prompt("Enter a number between 1 and 10:");
  if (input >= 1 && input <= 10) { // Exit if the input is valid
    break;
  }
  alert("Invalid input. Please try again.");
}
console.log(`Entered number: ${input}`);

关键要点:

  • 当满足条件时,循环使用 break 语句 退出。
  • 通过妥善管理无限循环的风险,能够安全地运行该过程。

4.5 使用调试工具

即使代码中出现错误,也可以通过开发者工具中的 debugger 或添加 console.log() 来检查运行情况。

示例:使用调试输出进行检查

let i = 0;
while (i < 5) {
  console.log(`Current value: ${i}`); // Debug output
  i++;
}

通过添加这样的输出,你可以在代码运行时验证循环的状态。

4.6 小结

本节阐述了无限循环的危害以及防止方法。

关键要点:

  • 当条件始终为真且从不改变时,会产生无限循环。
  • 通过明确定义退出条件并适当地更新变量,可以防止无限循环。
  • 需要时使用 break 安全退出循环。

5. 与 do…while 语句的比较

在 JavaScript 中,除了 while 语句,还有另一种循环结构叫做 do…while 语句。本节将比较两者,解释它们的区别,并展示何时使用每种语句。

5.1 do…while 语句的基本语法

do…while 语句 是一种循环结构,在评估条件之前至少执行一次代码

语法:

do {
  // Code to run
} while (condition);

关键要点:

  • 因为代码先执行,即使条件为 false 也至少执行一次
  • 条件在代码运行后才会被求值。

5.2 与 while 语句的区别

Featurewhile statementdo…while statement
When the condition is evaluatedAt the beginning (check before running)At the end (check after running)
Minimum number of executions0 times if the condition is falseRuns at least once even if the condition is false
Main use casesWhen the number of iterations is unknown in advanceWhen you must run the code at least once

5.3 使用 do…while 的示例

下面是一个验证用户输入的示例。

代码示例:

let input;
do {
  input = prompt("Enter a number from 1 to 10:");
} while (input < 1 || input > 10);

console.log(`Entered number: ${input}`);

关键要点:

  • 提示至少会显示一次。
  • 只要输入不满足条件,就会继续提示用户。

如果使用 while 重写:

let input = prompt("Enter a number from 1 to 10:");
while (input < 1 || input > 10) {
  input = prompt("Enter a number from 1 to 10:");
}
console.log(`Entered number: ${input}`);

对比:

  • while 语句: 需要在循环外先进行一次提示,因为条件先被检查。
  • do…while 语句: 由于第一次执行是必然的,代码可以更简洁。

5.4 何时应使用 do…while

  1. 必须至少运行一次的情况
  • 如表单验证等,需要至少执行一次的场景。
  1. 迭代次数动态决定的情况
  • 事先不知道需要重复多少次,而是想一直处理直到满足某个条件。

5.5 选择 while 与 do…while 的标准

ConditionRecommended statement
When you need to evaluate the condition before runningwhile statement
When you need to run the code at least oncedo…while statement

5.6 实际案例:密码输入验证

示例:使用 do…while 进行密码验证

let password;
do {
  password = prompt("Enter a password with at least 6 characters:");
} while (password.length < 6);

console.log("Password has been set!");

该代码会一直重复,直到用户输入的密码长度至少为 6 个字符。由于检查必须至少执行一次,do…while 非常合适。

如果使用 while 编写:

let password = "";
while (password.length < 6) {
  password = prompt("Enter a password (at least 6 characters):");
}
console.log("Password has been set!");

此时需要将第一次的值初始化为空字符串,使代码稍显冗长。

5.7 小结

本节阐述了 while 与 do…while 的区别,以及如何根据实际需求选择合适的循环结构。

关键要点:

  • while 语句: 先评估条件,只有在条件为真时才执行代码。
  • do…while 语句: 最后评估条件,保证代码至少执行一次。
  • 根据具体场景选择合适的循环,可让代码更简洁、更高效。

6. 实用示例:验证用户输入

本节将介绍使用 JavaScript 的 while 语句do…while 语句 进行用户输入验证的实用案例。对用户输入进行重复处理以确保提供正确信息,是网页应用和表单验证中的常见需求。

6.1 验证数值输入

该示例会反复弹出提示,直到用户输入的数字落在指定范围内。

代码示例(while 语句):

let number = parseInt(prompt("Enter a number from 1 to 10:"));

while (isNaN(number) || number < 1 || number > 10) {
  alert("Invalid input. Please enter a number from 1 to 10.");
  number = parseInt(prompt("Enter a number from 1 to 10:"));
}

console.log(`Entered number: ${number}`);

说明:

  1. 使用 prompt 获取用户输入。
  2. 当输入不是有效数字时,isNaN(number) 返回 true。
  3. 若条件不满足,弹出警告并再次请求用户输入。
  4. 循环会一直执行,直到条件满足为止。

6.2 验证密码长度

该示例会一直重复,直到用户输入的密码满足所需的长度条件。

代码示例(do…while 语句):

let password;

do {
  password = prompt("Enter a password with at least 6 characters:");
} while (password.length < 6);

console.log("Password has been set!");

Explanation:

  1. The prompt is always shown at least once.
  2. If the entered password is shorter than 6 characters, it requests input again.
  3. The loop ends once the condition is met.

Key points:

  • Using do…while allows you to skip the initial pre-check on the first input.
  • In real applications, you can add more checks such as character types or special symbols.

6.3 Email Address Validation with Repeated Prompts

This example validates the email format using a regular expression.

Code example (while statement):

let email = "";
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Email regex pattern

while (!emailPattern.test(email)) {
  email = prompt("Enter a valid email address:");
  if (!emailPattern.test(email)) {
    alert("Invalid email format. Please try again.");
  }
}

console.log(`Entered email address: ${email}`);

Explanation:

  1. Validate the email format using a regular expression.
  2. If the input does not meet the condition, ask the user to re-enter.
  3. The loop continues until the user enters a correctly formatted email address.

6.4 Input Validation with a Maximum Attempt Limit

This example avoids infinite loops by limiting the number of attempts.

Code example (while statement):

let username;
let attempts = 0; // Attempt counter
const maxAttempts = 3; // Maximum attempts

while (attempts < maxAttempts) {
  username = prompt("Enter your username:");
  if (username) {
    console.log(`Welcome, ${username}!`);
    break; // Exit loop if input is successful
  }
  attempts++; // Increase attempts
  alert(`Input is empty. Remaining attempts: ${maxAttempts - attempts}`);
}

if (attempts === maxAttempts) {
  console.log("Maximum attempts reached. Please try again later.");
}

Explanation:

  1. Set a maximum number of attempts and stop looping after the limit is reached.
  2. If valid input is provided, exit the loop immediately.
  3. Notify the user of the remaining attempts for better user experience.

6.5 Practical Application Example Using Input Validation

In real-world use cases such as form validation, you often combine JavaScript with HTML.

Code example (HTML + JavaScript):

HTML part:

<input type="text" id="username" placeholder="Enter your username" />
<button id="submitBtn">Submit</button>
<p id="errorMessage"></p>

JavaScript part:

document.getElementById("submitBtn").addEventListener("click", function () {
  let username = document.getElementById("username").value;
  let errorMessage = document.getElementById("errorMessage");

  if (username.length < 3) {
    errorMessage.textContent = "Username must be at least 3 characters long.";
  } else {
    alert(`Welcome, ${username}!`);
    errorMessage.textContent = ""; // Clear the error message
  }
});

This code can be used as a basic example of form input validation.

6.6 Summary

In this section, we introduced various practical examples of validating user input.

Key takeaways:

  • For validating numbers and passwords, using while or do…while is very useful.
  • Using regular expressions enables more advanced validation.
  • Adding attempt limits is important to prevent infinite loops.

7. Performance and Optimization Tips

In this section, we’ll explain performance and optimization tips to consider when using JavaScript’s while statement. Writing efficient code can improve execution speed and enhance the reliability and readability of your program.

7.1 Avoid Unnecessary Processing

Key point:
Avoid repeating the same calculations or operations inside a loop. Code that runs repeatedly can reduce performance.

Example: Inefficient code

let arr = [1, 2, 3, 4, 5];
let i = 0;

while (i < arr.length) {
  console.log(arr[i]);
  i++;
}

In this code, arr.length is recalculated each time the loop runs.

Improved example:

let arr = [1, 2, 3, 4, 5];
let length = arr.length; // Store array length in advance
let i = 0;

while (i < length) {
  console.log(arr[i]);
  i++;
}

Result:

  • By storing arr.length in a variable beforehand, you avoid recalculating it inside the loop and improve performance.

7.2 Optimize the Number of Loop Iterations

Key point:
To avoid unnecessary loops, carefully design the start value and the exit condition.

Example: Inefficient code

let i = 0;
while (i <= 100) {
  if (i % 2 === 0) {
    console.log(i);
  }
  i++;
}

Improved example:

let i = 0;
while (i <= 100) {
  console.log(i); // Print only even numbers
  i += 2; // Increment by 2
}

Result:

  • Adjusting the increment reduces unnecessary condition checks and improves code efficiency.

7.3 Detecting Infinite Loops and Debugging

Infinite loops can significantly reduce performance. If an infinite loop occurs during execution, use the browser or IDE debugger to identify the issue.

Debugging example:

let i = 0;
while (i < 10) {
  console.log(i); // Debug output
  // Infinite loop because i++ was forgotten
}

Improved example:

let i = 0;
while (i < 10) {
  console.log(i);
  i++; // Add increment to prevent an infinite loop
}

Tips for using debugging tools:

  1. console.log(): Print variable values inside the loop to track progress.
  2. Browser developer tools: Use debugging features in Chrome or Firefox, set breakpoints, and pause execution.
  3. Prepare for infinite loops: If execution becomes extremely slow, be ready to stop the process using the browser task manager.

7.4 Optimizing Nested Loops

Key point:
Nested loops can increase complexity and slow down execution. Be especially careful when processing large datasets.

Example: Inefficient code

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let results = [];

let i = 0;
while (i < arr1.length) {
  let j = 0;
  while (j < arr2.length) {
    results.push(arr1[i] * arr2[j]);
    j++;
  }
  i++;
}

Improved example:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let results = [];

arr1.forEach(a => {
  arr2.forEach(b => {
    results.push(a * b);
  });
});

Result:

  • Using forEach improves readability and can also help with maintainability.

7.5 Convert Repeated Logic into a Reusable Function

To avoid redundancy, you can wrap loop logic into a function so it can be reused easily.

Example: Optimization using a function

function printArrayElements(arr) {
  let i = 0;
  while (i < arr.length) {
    console.log(arr[i]);
    i++;
  }
}

const numbers = [10, 20, 30, 40];
printArrayElements(numbers);

Result:

  • Modularizing the logic prevents duplication and makes the code easier to maintain.

7.6 Summary

In this section, we introduced optimization tips for using JavaScript’s while statement efficiently.

Key takeaways:

  • Avoid unnecessary processing: Prevent repeated calculations such as checking array length inside the loop.
  • Optimize loop iterations: Adjust increments and conditions to reduce overhead.
  • Detect infinite loops and debug: Use debugging tools and console output for troubleshooting.
  • Optimize nested loops: Choose simpler and more efficient structures when possible.
  • Reuse code by using functions: Reduce redundancy and improve maintainability.

8. Summary

In this article, we explained JavaScript’s while statement in detail—from basic usage to practical examples and optimization tips. In this section, we’ll review what we covered and organize key points readers can apply in practice.

8.1 What You Learned in This Article

  1. 基本语法及 while 语句的工作原理
  • while 语句在条件为真时重复执行处理。
  • 由于条件先被评估,如果条件为假,循环一次也不会运行。
  1. 基本用法及实用示例
  • 固定次数循环: 对特定次数进行简单重复。
  • 重复直到满足条件: 用于输入验证和动态条件的灵活示例。
  • 处理数组元素: 处理数组和列表数据的具体示例。
  1. 如何避免无限循环
  • 无限循环可能导致程序卡死或崩溃。
  • 通过正确设计条件并使用 break,可以实现安全的循环逻辑。
  1. 与 do…while 语句的比较
  • do…while 语句: 一种无论条件如何都至少执行一次的循环结构。
  • 当需要至少执行一次时,do…while 非常有效。
  1. 实用的用户输入验证
  • 我们使用 while 和 do…while 对数字、密码和电子邮件地址进行验证。
  • 我们还介绍了尝试次数限制和基于正则表达式的验证示例。
  1. 性能与优化技巧
  • 我们学习了通过预先计算数组长度和条件来编写高效代码。
  • 我们还介绍了调试策略和嵌套循环的优化技术。

8.2 实用技巧

  1. 使用调试器:
  • 在开发者工具中使用调试器,实时检查循环内部的变量状态。
  1. 编写可复用代码:
  • 将逻辑封装到函数中,使其更易复用和管理。
  1. 保持条件简洁:
  • 编写清晰的条件,避免不必要的复杂性,以减少错误。
  1. 安全性设计:
  • 从一开始就考虑防止无限循环和错误处理,以避免运行时问题。

8.3 如何使用本文

本文可作为 JavaScript while 语句的综合指南,用于以下目的:

  • 初学者: 从头阅读,了解 while 循环的结构和行为。
  • 中级学习者: 使用实用示例和优化技巧来改进实际程序。
  • 开发者: 在验证逻辑或优化循环性能时将其作为参考。

8.4 后续步骤

在 JavaScript 中,除了 while 之外还有多种循环结构,如 forfor…of。了解每种结构并根据情况选择合适的工具,有助于编写更高效、可维护的代码。

接下来,学习以下主题将加深你的理解:

  1. 比较 for 与 for…of:
  • 学习更灵活的迭代处理方式。
  1. 使用数组方法(forEach、map、filter 等):
  • 简化代码并提升性能。
  1. 异步处理与循环:
  • 学习使用 async 函数进行任务重复的模式。

8.5 结束语

JavaScript 的 while 语句是一个强大的工具,可用于从基础到高级的各种场景。将本文作为参考,并通过自行编写和测试代码来加深理解。

实用技巧:

  • 从小示例开始,逐步尝试更高级的模式。
  • 使用调试工具确认代码的运行行为。
  • 在优化代码时始终牢记安全性和性能。
広告