(I) Import
To the page output consecutive numbers
var n = 1;
document.write(n++ +"<br />");
㈡while cycle
⑴ loop: can execute a piece of code repeated many times through the loop
⑵ syntax: the while (conditional expression) {
Statements...
}
⑶ execution process:
★ while statement is executed, the first conditional expressions are evaluated to determine:
① If true, the loop body is executed:
After the loop is finished, continued expression of judgment;
If true, then continue the loop, and so on
② If the value is false, the loop ends.
⑷ specific examples:
// write like this conditional expression is true cycle, called an infinite loop
// this cycle will not stop unless the browser is closed, endless loop with caution in development
// You can use the break, to terminate the loop
n. 1 = var;
the while (to true) {
Alert (n ++);
// determines whether n is 10
IF (n == 10) {
// exit the loop
BREAK;
}
}
⑸ create a cycle that often require three steps
1 // Create a variable initialization
var i = 0;
2 // Set a conditional expression in the loop
while(i < 10){
alert(i);
//3.定义一个更新表达式,每次更新初始化变量
i++;
}
具体示例:
var i = 1;
while(i <= 500){
document.write(i++ +"<br />")
}
㈢do. . . while循环
⑴语法:do{
语句. . .
}while(条件表达式)
⑵执行流程:
⑴do. . . while语句在执行时,会先执行循环体,
⑵循环体执行完毕以后,在对while后的条件表达式进行判断:
①如果结果为true,则继续执行循环体,执行完毕继续判断,以此类推
②如果结果为false,则终止循环
⑶示例:
do{
document.write(i++ +"<br />")
}while(i <= 10);
㈣两个语句的异同
实际上,这两个语句功能类似,不同的是:
⑴while是先判断后执行;而do. . .while会先执行后判断;
⑵do. . .while可以保证循环体至少执行一次,而while不能;
㈤代码练习
⑴问题:假如投资的年利率为5%,试求从1000块增长到5000块,需要花费多少年?
⑵代码如下:
//定义一个变量,表示当前的钱数
var money = 1000;
//定义一个计数器
var count = 0;
//定义一个while循环来计算每年的钱数
while(money < 5000){
money *= 1.05;
//使count自增
count++;
}
//console.log(money);
console.log("一共需要"+count+"年");