do while javascript 入門

do while javascript 入門

while

whileの意味はする間とかする限りです。
つまり条件式が満たされている間繰り返します。

while (条件式){
処理
}

<!DOCTYPE html>
<html lang=”ja”>
<head>
<meta charset=”UTF-8″>
<title>sample1</title>

<script type=”text/javascript”>
function helloworld(){

var i =3;
while (i < 9){
alert(i);
i++;
}
}
</script>
</head>
<body>
<form>
<input type=”button” value=”ここをクリック” onClick=”helloworld()”>
</form>

</body>
<html>

実行結果は3から8まで繰り返します。

もしインクリメントを書き忘れたらこの場合は無限ループになります。

do while

do whileは必ず1回は処理を実行します。

do{
処理
}while (条件式)

<!DOCTYPE html>
<html lang=”ja”>
<head>
<meta charset=”UTF-8″>
<title>sample1</title>

<script type=”text/javascript”>
function helloworld(){

var i =3;
do{
alert(i);
i++;
}while (i < 9)
}
</script>
</head>
<body>
<form>
<input type=”button” value=”ここをクリック” onClick=”helloworld()”>
</form>

</body>
<html>

実行結果は3から8まで繰り返します。

条件式が後ろにありますよね。

その時点で処理を判定しています。

条件式に満たさないとwhileは実行されませんが

do whileはdoの1回だけ実行されます。

<!DOCTYPE html>
<html lang=”ja”>
<head>
<meta charset=”UTF-8″>
<title>sample1</title>

<script type=”text/javascript”>
function helloworld(){

var i =10;
do{
alert(i);
i++;
}while (i < 9)
}
</script>
</head>
<body>
<form>
<input type=”button” value=”ここをクリック” onClick=”helloworld()”>
</form>

</body>
<html>

実行結果は10になります。

シェアする

  • このエントリーをはてなブックマークに追加

フォローする

Translate »