TypeScript While 循环
while 循环会在指定条件为真时执行指令。换句话说,在代码块被执行之前,循环会先评估条件。
语法
while(condition) {
// statements if the condition is true
}
流程图
示例:while循环
var num:number = 5;
var factorial:number = 1;
while(num >=1) {
factorial = factorial * num;
num--;
}
console.log("The factorial is "+factorial);
上面的代码片段使用一个 while 循环来计算变量num中的值的阶乘。
编译后,它将生成以下JavaScript代码−
//Generated by typescript 1.8.10
var num = 5;
var factorial = 1;
while (num >= 1) {
factorial = factorial * num;
num--;
}
console.log("The factorial is " + factorial);
它产生以下输出−
The factorial is 120