3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

for文とWhile文どっち??

Posted at

while文

index.html
<script>
    'use strict'

    let i = 0;
      while (i < 10) { 
        document.write( i+ '' );
        i++;
      }
<script>

for文

index.html
<script>
for (let i=0; i < 10; i++){
      document.write(i + '')
    }
<script>

どちらも同じ表示になるはずです。

スクリーンショット 2021-04-06 15.08.02.png

これどっちつかうの?ってなりますよね。

while文では、変数letを宣言していますね。
ということは、それ以後その変数を宣言することができません。

for文では、カウンター用の変数を使います。そのような変数は繰り返し処理の中でしか使わないことが多いです。なのでfor文の初期化式でカウンター変数を宣言すれば、for文の外からは使えない変数となりますので、プログラム全体が読みやすくなりますね!!

このように短いプログラムではわかりにくいですが、大きいプロジェクトになると、更に複雑化してくるので、For文とWhile文の使い分けはしっかりしたほうがいいですね👍

3
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?