LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptでもっと効率的に記述するfor文

Last updated at Posted at 2021-11-23

for文の書き方3選!

扱うリスト

const todos = [
    {
        id: 1,
        title: 'by some strawberries',
        completed: true
    },
    {
        id: 2,
        title: 'buy a fresh cream',
        completed: true
    },
    {
        id: 3,
        title: 'make a birthday cake',
        completed: false,
    },
]

出力したい結果

1 'by some strawberries'
2 'buy a fresh cream'

一般的なfor文

for(let i = 0; i < todos.length; i ++){
    let todo = todos[i];
    if(todo.completed == true){
        console.log(todo.id, todo.title)
    }
}

変数iの宣言/変数iの範囲/変数iの増加量とするごくごく一般的な、progateとかでよく扱われる方法。

inを使ったfor文

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

宣言した変数iを扱うのではなく、リストのアイテムごとに割り振られた添字扱ってリストを扱う。

ofを使ったfor文

for(let v of todos){
    if(v.completed == true){
        console.log(v.id, v.title)
    }
}

ofを使うとリストの中身でリストを扱うことができる。

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