U leest de Engelstalige versie van deze inhoud, omdat er nog geen vertaling voor deze taal beschikbaar is. Help ons dit artikel te vertalen!
The initial value of the @@iterator
property is the same function object as the initial value of the values()
property.
Syntax
arr[Symbol.iterator]()
Return value
The initial value given by the values()
iterator. By default, using arr[Symbol.iterator]
will return the values()
function.
Examples
Iteration using for...of
loop
var arr = ['a', 'b', 'c', 'd', 'e']; var eArr = arr[Symbol.iterator](); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of eArr) { console.log(letter); }
Alternative iteration
var arr = ['a', 'b', 'c', 'd', 'e']; var eArr = arr[Symbol.iterator](); console.log(eArr.next().value); // a console.log(eArr.next().value); // b console.log(eArr.next().value); // c console.log(eArr.next().value); // d console.log(eArr.next().value); // e
Use Case for brace notation
The use case for this syntax over using the dot notation (Array.prototype.values()
) is in a case where you don't know what object is going to be ahead of time. If you have a function that takes an iterator and then iterate over the value, but don't know if that Object is going to have a [Iterable].prototype.values method. This could be a built-in object like String object or a custom object.
function logIterable(it) { var iterator = it[Symbol.iterator](); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of iterator) { console.log(letter); } } // Array logIterable(['a', 'b', 'c']); // a // b // c // string logIterable('abc'); // a // b // c
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.prototype[@@iterator]()' in that specification. |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) The definition of 'Array.prototype[@@iterator]()' in that specification. |
Draft |
Browser compatibility
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@iterator | Chrome Full support 38 | Edge Full support 12 | Firefox
Full support
36
| IE No support No | Opera Full support 25 | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support 38 | Firefox Android
Full support
36
| Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support 0.12 |
Legend
- Full support
- Full support
- No support
- No support
- See implementation notes.
- See implementation notes.
- Uses a non-standard name.
- Uses a non-standard name.