LoginSignup
0
0

More than 3 years have passed since last update.

[JS] ループ

Posted at

for文

const arry = [1,2,3,4,5];

for(let i = 0; i < 5; i = i + 1) {
  console.log(i);
}

Image from Gyazo

let i = 0;   変数を定義
i < 5;     ループを継続する条件を指定
i = i + 1   ブロックが一回終了したときに実行される式


arry[ i ]とすれば、配列の要素を回すことができます

const arry = [1,2,3,4,5];

for(let i = 0; i < arry.length; i ++) {
  console.log(arry[i]);
}

Image from Gyazo

i < arry.length;
i ++

for in

in arryとすると配列のインデックスが渡ってきます

const arry = [1,2,3,4,5];

for(let i in arry) {
  console.log(i);
}

Image from Gyazo


i, arry[ i ]とすると値を一括で見ることもできます

const arry = [1,2,3,4,5];

for(let i in arry) {
  console.log(i, arry[i]);
}

Image from Gyazo

for of

for ofは値がそのまま渡ってきます
現在対応していないブラウザがありますのでご注意ください

const arry = [1,2,3,4,5];

for(let v of arry) {
  console.log(v);
}

Image from Gyazo

オブジェクトのループ

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(let i = 0; i < todos.length; i++) {
  console.log(todos[i]);
}

Image from Gyazo


if文を使って、ToDoの中で、タスクが完了しているもののタイトルだけ出力する

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(let i = 0; i < todos.length; i++) {
  let todo = todos[i];
  if (todo.completed === true) {
    console.log(todo.title);
  }
}

Image from Gyazo


inとofも使えます

for(let i in todos) {
  let todo = todos[i];
  if (todo.completed === true) {
    console.log(todo.title);
  }
}
for(let i of todos) {
  let todo = todos[i];
  if (todo.completed === true) {
    console.log(todo.title);
  }
}
0
0
0

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
0
0