LoginSignup
3
3

More than 3 years have passed since last update.

for, for in, for of, forEach まとめ

Posted at

for

  • 基本的な書き方
const colors = ["red", "yellow", "green"]

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

for of

  • ES6
  • for文をより簡潔に記述できる
  • 配列要素の繰り返し処理
const colors = ["red", "yellow", "green"]

for(color of colors){
    console.log(color)
}

for in

  • ES6
  • ブジェクトのプロパティ(キー)分ループしてくれる
const colors = { one: "red", two: "yellow", three: "green" }

for (key in colors) {
  console.log(`${key} : ${colors[key]}`)
}

forEach

  • ES6
  • 配列要素の繰り返し処理(for of と同じ)
  • コールバック関数を切り離して記述できる
const numbers = [1, 2, 3, 4, 5]
let sum = 0

const adder = (number) => (sum += number)
numbers.forEach(adder)
console.log(sum)
3
3
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
3
3