Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(loop): for...of文について #95

Merged
merged 17 commits into from
Jul 20, 2016
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions source/basic/loop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,54 @@ console.log(total); // => 1
このようにfor...in文は正しく扱うのが難しいですが、代わりとなる手段が豊富にあります。
そのため、for...in文を使うことよりも他の方法を考えた方がよいでしょう。

## [ES2015] for...of文

最後にfor...of文についてです。

JavaScriptでは、`Symbol.iterator`という特別な名前のメソッドを実装したオブジェクトをiterableと呼びます。
iterableオブジェクトはfor...of文で反復処理が可能になります。

iterableについてはgeneratorと密接な関係がありますが、ここでは反復処理時の動作が定義されたオブジェクトと認識していれば問題ありません。

iterableオブジェクトはfor...of文で値を列挙することができます。
for...of文では、`iterable`から列挙可能な値を1つ取り出し、`variable`に代入し反復処理されます。
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここで、上手く iterable は反復処理時に、次にどの値を取り出して欲しいかを定義したもの
って話が自然と入ると説明が全部できてる


```js
for (variable of iterable)
処理する文;
```

実はすでにiterableオブジェクトは登場しています。

ArrayやStringなどはiterableオブジェクトであるため、次のようにfor...of文で反復処理ができます。
for...in文とは異なり、添字ではなく値を列挙します。
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

添字とindexとindex値 迷ってる気がする。
添字だと値っぽい感じがしない

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

添字って聞くと表記法って印象があるけどそうでもないのかな


```js
var array = [1, 2, 3];
for (var value of array) {
console.log(value);
}
// 1
// 2
// 3
```

JavaScriptではStringオブジェクトもiterableです。
サロゲートペアも考慮し1文字ずつ値を列挙することができます。

```js
var string = "吉野家";
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"吉野家" じゃない サロゲートペアな文字列欲しい(短めで意味があり、サロゲートペアの例としてよくあがり、商標とかではないもの)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

𩸽 (ホッケ)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for (var value of string) {
console.log(value);
}
// "吉"
// "野"
// "家"
```

その他にも、`TypedArray`、`Map`、`Set`、DOM NodeListなど、JavaScriptではiterableなオブジェクトが多くあります。
for...of文はそれらに対して反復処理を行うことができます。

## [コラム] `let`ではなく`const`で反復処理をする

先ほどのfor文や`forEach`メソッドでは`let`を`const`に変更することはできませでした。
Expand Down