In ES6, an iterable is an object that allows for... of
, and has a Symbol.iterator key.
Arrays are iterables, as are Sets and Maps. The question is: are
Unfortunately, not yet. But until they are, you can easily polyfill them like so:
HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
Symbol.iterator
support for NodeList
, HTMLCollection
, DOMTokenList
, and DOMSettableTokenList
was discussed and added to the WHATWG's DOM spec last year.
For anyone arriving here from trying to iterate on NodeList using TypeScript. I found this issue with the fix https://github.com/microsoft/TypeScript/issues/4947 and this is the tsconfig.json
you'll need for it:
{
"compilerOptions": {
"lib": ["es2017", "dom", "dom.iterable"],
"downlevelIteration": true
}
}
The problem error I was getting:
Type 'NodeListOf<Element>' is not an array type.
And this was the code that was triggering that problem:
[...document.querySelectorAll('#md-view a')]
As greiner pointed out, native Symbol.iterator
support for NodeList
was added to the WHATWG's DOM spec in 2014.
Unfortunately, Chrome 51 is the first version of Chrome to support it, and its Beta has only just been released at the time of writing this answer. Also, there's no support in any version of Internet Explorer or Edge.
To add Symbol.iterator
support for NodeList
in all browsers to your code, just use the following polyfill :
NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];