JavaScript Tutorial/Statement/while — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 08:25, 26 мая 2010
Содержание
Check the loop counter for while loop
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var i = 1;
while (i < 101) {
if (i == 99) {
alert("The number is " + i);
}
i++;
}
</script>
</body>
</html>
Nesting If statement to a while statement
<html>
<head>
<title>Number Guesser</title>
<script>
var guess = 50;
var target = 0;
var turns = 0;
var msg = "";
target = Math.floor(Math.random() * 100) + 1;
guess = eval(prompt("What is your guess?", guess));
while (guess != target){
turns++;
if (guess > target){
guess = eval(prompt (turns + ". Too high!! Next guess?", guess));
}
if (guess < target){
guess = prompt (turns + ". Too low!! Next guess?", guess);
}
if (guess == target){
msg = "YOU WIN!!! \n";
msg += "It took you ";
msg += turns + " turns! ";
alert (msg);
}
}
</script>
</head>
Use Do while loop to reverse a string
<HTML>
<BODY>
<H1>
<SCRIPT>
var newString = "";
var theString = "abcde";
var counter = theString.length;
do
{
newString += theString.substring(counter-1, counter);
counter--;
}
while (counter > 0 );
document.write(theString + " reversed is " + newString + "!");
</SCRIPT>
</H1>
</BODY>
</HTML>
Use integer variable to control the while loop
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 1
while (x < 10)
{
++x;
alert(x);
}
// -->
</script>
</head>
<body>
</body>
</html>
Use while loop to output all elements in an array
<html>
<head>
<title>Use while loop to output all elements in an array</title>
</head>
<body>
<h1>Use while loop to output all elements in an array</h1>
<script language="javascript" type="text/javascript">
<!--
var ages = new Array(12,57,32,6,21,19);
var i=0;
while (ages.length) {
var tempAge = ages.pop();
document.write("<P>" + tempAge + "</p>");
}
//-->
</script>
</body>
</html>
Using While loop to check user input
<html>
<head>
<title>Using While loop to check user input</title>
<script>
var correct = "AA";
var guess = "";
while (guess != correct){
guess = prompt ("Question?", "");
if (guess == correct){
alert ("Correct");
} else {
alert ("that"s not it...");
}
}
</script>
</head>
<body>
</body>
</html>
while loop
The while loop can be summarized as while the expression evaluates to true, execute the statements in the loop.
Once the last statement in the loop is executed, go back to the top of the loop and evaluate the expression again.
When the expression evaluates to false, the next line of code following the while loop structure is executed.
Because the expression is evaluated before the loop, it is possible the loop will never be executed.
The format of the while loop looks like the following:
while (expression)
{
statement;
}