The @@iterator
method is part of The iterable protocol, that defines how to synchronously iterate over a sequence of values.
The @@iterator
method is part of The iterable protocol, that defines how to synchronously iterate over a sequence of values.
The initial value of the @@iterator
property is the same function object as the initial value of the values()
property.
[Symbol.iterator]()
<ul id="letterResult"> </ul>
const arr = ['a', 'b', 'c']; const arrIter = arr[Symbol.iterator](); const letterResult = document.getElementById('letterResult'); for (const letter of arrIter) { const li = document.createElement('li'); li.textContent = letter; letterResult.appendChild(li); }
const arr = ['a', 'b', 'c', 'd', 'e']; const arrIter = arr[Symbol.iterator](); console.log(arrIter.next().value); // a console.log(arrIter.next().value); // b console.log(arrIter.next().value); // c console.log(arrIter.next().value); // d console.log(arrIter.next().value); // e
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) { if (!(Symbol.iterator in it)) { console.log(it, ' is not an iterable object.'); return; } const iterator = it[Symbol.iterator](); for (const letter of iterator) { console.log(letter); } } // Array logIterable(['a', 'b', 'c']); // a // b // c // string logIterable('abc'); // a // b // c logIterable(123); // 123 is not an iterable object.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
@@iterator |
38 |
12 |
36
27-36
A placeholder property named
@@iterator is used.17-27
A placeholder property named
iterator is used. |
No |
25 |
10 |
38 |
38 |
36
27-36
A placeholder property named
@@iterator is used.17-27
A placeholder property named
iterator is used. |
25 |
10 |
3.0 |
1.0 |
0.12.0 |
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator