728x90
SMALL
#javascript
#JavaScript / Repeat Statements / while, do - while, for
There are three iteration statements in JavaScript: while, do - while, and for.
while
grammar
var i = 0;
while ( i < 10 ) {
// do something
i++;
}
It runs from 0 to 9 for i and if i is 10 it doesn't run and goes on.
Note that you must include i++ which increments i. If i++ is missing, the value of i will always be 0, so it will repeat infinitely. Do - while and for are similar.
example
This is an example of outputting from 1 to 10 using while.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<p>
<script>
var i = 0;
while ( i < 10 ) {
document.write( i + ' ' );
i++;
}
</script>
</p>
</body>
</html>
do - while
grammar
var i = 0;
do {
// do something
i++;
} while ( i < 10 )
Similar to while. The difference is that it runs once regardless of the value of i.
example
Here is an example of using do - while to print from 1 to 10.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<p>
<script>
var i = 0;
do {
document.write( i + ' ' );
i++;
} while ( i < 10 )
</script>
</p>
</body>
</html>
for
grammar
for ( var i = 0; i < 10; i++ ) {
// do something
}
example
Here is an example of using for to output from 1 to 10.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<p>
<script>
for ( var i = 0; i < 10; i++ ) {
document.write( i + ' ' );
}
</script>
</p>
</body>
</html>
728x90
LIST
'Javascript' 카테고리의 다른 글
[JavaScript] JavaScript / Global Variables and Local Variables (0) | 2022.08.03 |
---|---|
[JavaScript] Declare and call javascript/function/function (0) | 2022.08.02 |
[JavaScript] JavaScript/conditional statement/switch (0) | 2022.08.01 |
[JavaScript] JavaScript / Conditionals / if, else if, else (0) | 2022.08.01 |
[JavaScript] JavaScript/operator/typeof operator (0) | 2022.08.01 |