Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 92e664b

Browse files
authored
Added Iterables and iterators
1 parent 26b33a9 commit 92e664b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎README.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
8. [Class](#class)
1111
9. [Promises](#promises)
1212
10. [Maps and Sets](#maps-and-sets)
13+
11. [Iterables and iterators](#iterables-and-iterators)
1314

1415
## Variable scope
1516

@@ -1107,3 +1108,42 @@ ws.add(bar);
11071108
ws.has(foo); // true
11081109
ws.has(bar); // true
11091110
```
1111+
1112+
## Iterables and iterators
1113+
ES6 introduces a new mechanism for traversing data: iteration. Two concepts are central to iteration:
1114+
* An iterable is a data structure that wants to make its elements accessible to the public. It does so by implementing a method whose key is Symbol.iterator. That method is a factory for iterators.
1115+
* An iterator is a pointer for traversing the elements of a data structure (think cursors in databases).
1116+
1117+
`String`, `Array`, `TypedArray`, `Map` and `Set` are all built-in iterables, because each of their prototype objects implements an `@@iterator` method.
1118+
1119+
### User-defined iterables
1120+
We can make our own iterables like this:
1121+
```
1122+
var myIterable = {};
1123+
myIterable[Symbol.iterator] = function* () {
1124+
yield 1;
1125+
yield 2;
1126+
yield 3;
1127+
};
1128+
[...myIterable]; // [1, 2, 3]
1129+
```
1130+
### Simple Iterator for an Array
1131+
```
1132+
function makeIterator(array) {
1133+
var nextIndex = 0;
1134+
1135+
return {
1136+
next: function() {
1137+
return nextIndex < array.length ?
1138+
{value: array[nextIndex++], done: false} :
1139+
{done: true};
1140+
}
1141+
};
1142+
}
1143+
1144+
var it = makeIterator(['yo', 'ya']);
1145+
1146+
console.log(it.next().value); // 'yo'
1147+
console.log(it.next().value); // 'ya'
1148+
console.log(it.next().done); // true
1149+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /