for文とWhile文どっち??
2663 ワード
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>
index.html
<script>
'use strict'
let i = 0;
while (i < 10) {
document.write( i+ '枚' );
i++;
}
<script>
index.html
<script>
for (let i=0; i < 10; i++){
document.write(i + '枚')
}
<script>
どちらも同じ表示になるはずです。
これどっちつかうの?ってなりますよね。
while文では、変数letを宣言していますね。
ということは、それ以後その変数を宣言することができません。
for文では、カウンター用の変数を使います。そのような変数は繰り返し処理の中でしか使わないことが多いです。なのでfor文の初期化式でカウンター変数を宣言すれば、for文の外からは使えない変数となりますので、プログラム全体が読みやすくなりますね!!
このように短いプログラムではわかりにくいですが、大きいプロジェクトになると、更に複雑化してくるので、For文とWhile文の使い分けはしっかりしたほうがいいですね👍
Author And Source
この問題について(for文とWhile文どっち??), 我々は、より多くの情報をここで見つけました https://qiita.com/akari_0618/items/db574e4e2478bf5c6e14著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .