Content deleted Content added
Maxeto0910 (talk | contribs) No edit summary Tags: Mobile edit Mobile web edit Advanced mobile edit |
explain iterators better |
||
Line 430:
</syntaxhighlight>
There are also ''well known symbols''. <!-- TODO: Add table or something -->
One of which is <code>Symbol.iterator</code>; if something implements <code>Symbol.iterator</code>, it's iterable:
<syntaxhighlight lang="javascript">
let x = [1, 2, 3, 4]; // x is an Array
</syntaxhighlight>▼
const xIterator = x[Symbol.iterator](); // The [Symbol.iterator] function should provide an iterator for x
xIterator.next(); // { value: 1, done: false }
xIterator.next(); // { value: 2, done: false }
xIterator.next(); // { value: 3, done: false }
xIterator.next(); // { value: 4, done: false }
xIterator.next(); // { value: undefined, done: true }
xIterator.next(); // { value: undefined, done: true }
// for..of loops automatically iterate values
for (const value of x) {
console.log(value); // 1 2 3 4
}
// Sets are also iterable:
[Symbol.iterator] in Set.prototype; // true
for (const value of new Set(['apple', 'orange'])) {
console.log(value); // "apple" "orange"
}
▲</syntaxhighlight>
==Native objects==
|