LoginSignup
3
4

More than 5 years have passed since last update.

基本文法(繰り返し処理)

Last updated at Posted at 2015-06-17

繰り返し処理

繰り返しにはforwhiledo whileがある。

繰り返し構文 説明
for 繰り返しの回数があらかじめ決まっている場合(配列の繰り返し)におすすめ
while 繰り返し回数があらかじめ決められない場合におすすめ
do while 必ず最初の1回は繰り返し処理を実行させたい場合に利用

for

forは条件が真の間だけ与えられた文の実行を繰り返すというループを記述するための文である。

構文

for( 初期化式; 条件式; 増減式 ){
    //繰り返し処理
}

while

while文は()の条件がtrueであり続ける間ループする。
※間違えると無限ループになるので要注意。

var i = 0;
while ( i < 10 ) {
    document.write( i + '<br/>' ) ;
    i ++ ; // これをいれないと無限にループする
}

do while

do whileは少なくとも1回は実行され、()の条件がtrueであり続ける間ループする。

do {
   i += 1;
   document.write(i);
} while (i < 5);

break(処理の中断)

forwhileは条件がtrueの間繰り返し処理するが、途中で中断することもできる。
中断したい箇所でbreakを入れると中断する。

var mnt = new Array("富士山","白根山","奥穂高岳","間ノ岳","槍ヶ岳");
for(var i=0 ; i < mnt.length; i++){
    document.write( mnt[i] + '</br>');
    if(mnt[i] == "間ノ岳"){
        break; // 繰り返し処理を中断
    }
}

continue(次の処理に移動)

繰り返し処理の中でcontinueを指定すると、それいこうの処理は実行せずに次の繰り返し処理に移動する。
forwhiledo whilefor ifの中でしか使用することはできない。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4