The following works on the JavaScript runtimes I've checked (Node.js and Firefox):
let xs = [0, 1, 2]
let it = xs[Symbol.iterator]()
for (let x of it) console.log(x)
This works because the it
iterator is itself iterable, ie it has a Symbol.iterator
property. One could presume this is because Array.prototype[Symbol.iterator]
is implemented as a generator.
My question is, can I rely on it
being iterable? That is, is it required by the spec?
I've looked ( this is the relevant part, I think) and I can't find anything that says that an array iterator should be iterable, or that it must be implemented with a generator.
You can! All standard iterators for core objects extend %IteratorPrototype%
which specifically defines:
The following steps are taken:
- Return the
this
value.The value of the
name
property of this function is[Symbol.iterator]
.
So every builtin iterator will automatically return itself when used as an iterable, so using it in a for...of
or any other iteration context is safe.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.