您的位置:寻梦网首页编程乐园JavaScriptJavascript入门到精通
Javascript 入门到精通

第 1 天 第 2 天 第 3 天 第 4 天 第 5 天
第2页:循环入门
作者:Thau!
有时你想反复做同一件事。你想向某些人询问一个口令,你不断地问,直到得到正确的口令。如果你只想给他们两次尝试的机会,你可以这么做:

var the_password = "pass the wrench";

var answer = prompt("What's the woyd?","");

if (answer != the_password) {

    answer = prompt("What's the woyd?","");

    if (password != the_password) {

        document.write("You lose!<p>");

    } else {

        document.write("That's right!<p>");

    }

} else {

    document.write("That's right!<p>");

}

 

 

不幸的是如果你想不住地问直到得到正确答案,上述做法是不起作用的。假使你是想询问四次而不是两次,那这已经是很讨厌的事了。你将使用四个层次的if-then 子句,这决不是件好事。

反复做相似的事情的最好方法是使用一个循环(loop)。在这种情况下,你可以用一个循环来不断的要求口令直到这个人说出为止。这里有一个while循环工作的例子,口令是:pass the wrench.


Page 1: 第四课介绍
Page 2: 循环介绍
Page 3: 循环的密码
Page 4: 再谈 WHILE循环
Page 5: For 循环
Page 6: 嵌套循环
Page 7: 循环练习
Page 8: 数组
Page 9: 数组和循环
Page 10: 文件目标模块中的数组
Page 11: 函数
Page 12: 无参数函数
Page 13: 参数及返回值
Page 14: 多于一个参数的函数


本内容由搜狐网站(www.sohoo.com.cn)提供。