javaScript for文基礎

2020年12月21日

javaScript for文基礎

それとなくまとめておきたいと思います。

参考:
  ・【JavaScript入門】forEach文の使い方と配列の繰り返し処理まとめ!
  ・【初心者必見】JavaScriptのfor-in文でオブジェクトの繰り返しを極める!

カウンタ式


for(let i = 0; i < 10; i++){
    console.log(i);
}
//実行結果
//test.html:5 0
//test.html:5 1
//test.html:5 2
//test.html:5 3
//test.html:5 4
//test.html:5 5
//test.html:5 6
//test.html:5 7
//test.html:5 8
//test.html:5 9

const alphabets = ['a', 'b', 'c', 'd', 'e']
for(let i = 0; i < alphabets.length; i++){
    console.log(alphabets[i]);
}
//結果
//test.html:6 a
//test.html:6 b
//test.html:6 c
//test.html:6 d
//test.html:6 e

forIn式


const alphabets = ['a', 'b', 'c', 'd', 'e']
for(index in alphabets){
    console.log(alphabets[index])
}
//結果
//test.html:6 a
//test.html:6 b
//test.html:6 c
//test.html:6 d
//test.html:6 e

var fruits = [
    {name: 'バナナ', price: '100'},
    {name: 'リンゴ', price: '200'},
    {name: 'メロン', price: '300'},
    {name: 'ブドウ', price: '400'},
];
for(index in fruits){
    console.log(fruits[index].name)
}
//結果
//test.html:11 バナナ
//test.html:11 リンゴ
//test.html:11 メロン
//test.html:11 ブドウ

forEach式


var fruits = [
    {name: 'バナナ', price: '100'},
    {name: 'リンゴ', price: '200'},
    {name: 'メロン', price: '300'},
    {name: 'ブドウ', price: '400'},
];
fruits.forEach(function(value){
    console.log(value.name);
});
//結果
//test.html:11 バナナ
//test.html:11 リンゴ
//test.html:11 メロン
//test.html:11 ブドウ
YouTube

2020年12月21日