TypeScript while 和 do...while 循环

注意: 如果您是 TypeScript 新手,请先查看我们的 TypeScript 入门 教程。


TypeScript while 循环

while 循环在指定的条件为 true 时,会重复执行一段代码。

while 循环的语法是

while (condition) {
    // Body of loop
}

这里,

  1. while 循环首先计算 ( ) 中的 条件
  2. 如果 条件 计算结果为 true,则执行 { } 中的代码。
  3. 然后,再次计算 条件
  4. 只要 条件 计算结果为 true,这个过程就会持续进行。
  5. 如果 条件 计算结果为 false,则循环停止。

while 循环流程图

Flowchart of while loop in TypeScript
TypeScript while 循环流程图

示例 1:显示从 1 到 3 的数字

// Initialize variable i
let i: number = 1;

// Loop runs until i is less than 4
while (i < 4) {
    console.log(i);

    // Increase value of i by 1
    i += 1;
}

输出

1
2
3

以下是循环的每次迭代程序的工作方式

变量 条件:i操作
i = 1 true 打印 1i 增加到 2
i = 2 true 打印 2i 增加到 3
i = 3 true 打印 3i 增加到 4
i = 4 false 循环终止。

要了解有关循环条件的更多信息,请访问 TypeScript 比较和逻辑运算符


示例 2:仅正数的总和

let inputNumber: number = 0;
let sum: number = 0;

// Create a variable to take user input
// The variable can be either string or null 
let userInput: string | null;

// Loop as long as inputNumber is not negative while (inputNumber >= 0) { // Add all positive numbers sum += inputNumber;
// Take input from the user // prompt() returns either string or null userInput = prompt("Enter a number: "); // Convert userInput to number inputNumber = Number(userInput); } // Display the sum outside the loop console.log(`The sum is ${sum}`);

输出

Enter a number: 2
Enter a number: 4
Enter a number: -3
The sum is 6

上面的程序提示用户输入一个数字。

由于 TypeScript 的 prompt() 函数只接收字符串作为输入,我们使用 Number() 函数将输入转换为数字。

注意:如果用户没有输入任何内容(通过按 取消 按钮),prompt() 将返回 null。在这种情况下,按 取消 将退出循环,因为 null 不会被转换为有效数字。

只要我们输入正数,while 循环就会将它们加起来,并提示我们输入更多数字。

所以当我们输入一个负数时,循环终止。

最后,我们在循环外部显示正数的总和。

注意:当我们相加两个或多个数字字符串时,TypeScript 会将它们视为字符串。例如,"2" + "3" = "23"。因此,为了避免意外行为,我们应该始终将数字字符串转换为数字。


TypeScript do...while 循环

do...while 循环会先执行一次代码块,然后只要指定的条件为 true,就会重复执行它。

do...while 循环的语法是

do {
    // Body of loop
} while(condition);

这里,

  1. do…while 循环会执行 { } 中的代码。
  2. 然后,它会计算 ( ) 中的 条件
  3. 如果 条件 计算结果为 true,则再次执行 { } 中的代码。
  4. 只要 条件 计算结果为 true,这个过程就会持续进行。
  5. 如果 条件 计算结果为 false,则循环终止。

do...while 循环流程图

Flowchart of do...while loop in TypeScript
TypeScript do...while 循环流程图

示例 3:显示从 3 到 1 的数字

let i: number = 3;

// Loop body is executed first
// Then, loop continues as long as i is positive
do {
    console.log(i);

    // Decrement value of i by 1
    i--;
} while (i > 0);

输出

3
2
1

在这里,i 的初始值为 3。然后,我们使用 do...while 循环迭代 i 的值。以下是循环的每次迭代的工作方式

操作 变量 条件:i > 0
打印 3i 减为 2 i = 2 true
打印 2i 减为 1 i = 1 true
打印 1i 减为 0 i = 0 false
循环终止。 - -

while 和 do...while 循环之间的区别

while 和 do...while 循环有什么区别?

whiledo...while 之间的区别在于,do...while 循环至少会执行其主体一次。例如,

let i: number = 5;

// False condition
// Body executes once
do {
    console.log(i);
} while (i > 10);

// Output: 5

另一方面,如果循环条件为 falsewhile 循环不会执行其主体。例如,

let i: number = 5;

// False condition
// Body not executed
while (i > 10) {
    console.log(i);
};

示例 4:正数的总和

let inputNumber: number = 0;
let sum: number = 0;

// Create a variable to take user input
// The variable can be either string or null 
let userInput: string | null;

do {

    // Add all positive numbers
    sum += inputNumber;

    // Take input from the user
    userInput = prompt("Enter a number: ");

    // Convert userInput to number
    inputNumber = Number(userInput);

    // Loop terminates if inputNumber is negative
} while (inputNumber >= 0);

// Finally, display the sum
console.log(`The sum is ${sum}`);

输出

Enter a number: 2
Enter a number: 4
Enter a number: -3
The sum is 6

在上面的程序中,do...while 循环提示用户输入一个数字。

只要我们输入正数,循环就会将它们相加,并提示我们输入更多数字。

如果我们输入一个负数,循环将终止,而不会将负数相加。


更多关于 TypeScript while 和 do...while 循环

TypeScript 中的无限 while 循环是什么?

无限 while 循环是指循环无限运行的条件,因为其条件始终为 true。例如,

let i: number = 1;

// Condition is always true
while(i < 5) {
    console.log(i);
}

此外,这里有一个无限 do...while 循环的例子

let i: number = 1;

// Condition is always true
do {
    console.log(i);
} while (i < 5);

在上面的程序中,条件 i < 5 始终为 true,这导致循环体永远运行。

注意:无限循环可能导致程序崩溃。因此,请避免无意中创建它们。

for 和 while 循环有什么区别?

1. for 循环

当我们知道所需的迭代次数时,我们使用 for 循环。例如,

// Display "hi" 3 times

for (let i: number = 1; i <= 3; i++) {
    console.log("hi");
}

console.log("bye");

输出

hi
hi
hi
bye

在这里,我们知道需要打印 "hi" 三次。因此,我们使用了 for 循环而不是 while 循环。

2. while 循环

与此同时,当我们需要的终止条件可能会发生变化时,我们使用 while 循环。例如,

// Boolean variable to use as condition
let isDisplay: boolean = true;

// Variable to take user input from prompt()
// Can be either string or null
let userChoice: string | null;

// Display "hi" as long as user wants
// Basically, run the loop as long as isDisplay is true
while (isDisplay) {

    console.log("hi");

    // Get user input
    userChoice = prompt("print hi again? y for yes: ");

    // Set isDisplay to false if userChoice is not "y" or if it's null
    if (userChoice != "y" || userChoice === null)
        isDisplay = false;
}

console.log("bye");

输出

hi
print hi again? y for yes: y
hi
print hi again? y for yes: y
hi
print hi again? y for yes: n
bye

在上面的程序中,我们让用户随意打印 "hi"

由于我们不知道用户的决定,所以我们使用 while 循环而不是 for 循环。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战