for( let i in 配列名) :添字がi に格納されるfor( let v of 配列名) :配列の値がv に格納される<aside>
⚠️ 変数i は開発者間では添字に対してつけるイメージになっている。
従ってfor ofではv などの他の文字を変数名にした方がよい。
</aside>
<aside>
⚠️ for of は一部ブラウザに対応していない。特に古いブラウザ。使用する際は注意すること。(対応させるには、webpackやバベルを使って昔の記述に変換する必要あり)
</aside>
例)
const arry = ['taro','himura','shitara'];
// for in
for (let i in arry) {
console.log(i);
}
→ 0
1
2
for (let i in arry) {
console.log(arry[i]);
}
→ taro
himura
shitara
// for of
for (let v of arry) { // iは添字の変数名というイメージ。for ofだと値が取得できるので、i以外の文字を変数名にする
console.log(v);
}
→ taro
himura
shitara
例2)for of はこちらの方が理解しやすいかも。
//配列
const todos = [
{
id: 1,
title: 'Go to school',
completed: true
},
{
id: 2,
title: 'Go to museum',
completed: true
},
{
id: 3,
title: 'Go shopping',
completed: false
}
]
// for of
for(let **todo** of todos) { //todoでtodosに格納されているオブジェクト一つ一つを取得できている
if(todo.completed === true) {
console.log(todo.title);
}
}
// 上記を普通のfor文で書いた場合
for(let i = 0; i < todos.length; i++) {
const todo = todos[i];
if(todo.completed === true) {
console.log(todo.title);
}
}