for文
for(初期化値;ループ継続条件式;増減式){
繰り返し実行したい処理
}
(例)
for(let i = 1; i <= 3; i++){
console.log(i);
}
出力結果→1,2,3
for文の流れ
①iの初期値1が出力せれる。
②i <= 3以下なので、i++が実行され1+1の結果2が出力される。
③i <= 3を満たすまで繰り返す。
④終了したらfor文の下の記述が実行させる。
*配列は0から始まるので配列が3の場合は3未満なので、<3か <=2と記入する。
let arr = ['red','green','blue'];
for(let i = 0; i < 3; i++){
console.log(arr[i]);
}
*継続条件式にlengthを記入する事で、配列が何個増えても記述を変更できなくて良い。
let test = ['name','tel','gender','birthYear']
for(let i = 0; i<test.length; i++){
console.log(test[i]);
}
for文の入れ子構造
const scores = [
[100,99,98,],
[90,89,87,],
[80,79,78,],
];
for(let i = 0; i <scores.length; i++){
for(let j = 0; j <scores.length; j++){
console.log(scores[i][j]);
}
}
while文
let j = 1;
while (j <= 5){
console.log(j);
j++;
}
出力結果1,2,3,4,5
① j <= 5を満たしていないので、console.log(i)が出力される。
② j++により、1+1=2が実行され、console.log(i)が出力される。
③ j <= 5を満たすまで繰り返し。
*j++を忘れると、 j=1が永遠に出力させるので注意。
forEach文
配列名.forEach(コールバック関数)(要素の値){
実行したい処理
}
let colors = ['red','green','blue'];
colors.forEach(function(color){
console.log(color);
});