LoginSignup
1
1

More than 3 years have passed since last update.

JSのfor in,for ofについて

Last updated at Posted at 2020-08-01

最近までfor inしか使ってなかったのでまとめるよ

for inの場合

for inはインデックス番号が入るだけ

const users = [
    {
        id: 1,
        name: 'hiroto',
        age: 21,
    },
    {
        id: 2,
        name: 'hiroko',
        age: 40,
    },
    {
        id: 3,
        name: 'hiroshi',
        age: 12,
    }
]

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

//結果

0
1
2

for ofの場合

値が入る

const users = [
    {
        id: 1,
        name: 'hiroto',
        age: 21,
    },
    {
        id: 2,
        name: 'hiroko',
        age: 40,
    },
    {
        id: 3,
        name: 'hiroshi',
        age: 12,
    }
]

for(let user of users) {
    console.log(user);
}

//結果

{id: 1, name: "hiroto", age: 21}
{id: 2, name: "hiroko", age: 40}
{id: 3, name: "hiroshi", age: 12}

単純明快、for inばっかり使ってたからなんか汚かったんだなぁ

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