DOM4 使NodeList https://www.w3.org/TR/dom/#interface-nodelist可迭代:
interface NodeList {
getter Node https://www.w3.org/TR/dom/#node? item https://www.w3.org/TR/dom/#dom-nodelist-item(unsigned long index);
readonly attribute unsigned long length https://www.w3.org/TR/dom/#dom-nodelist-length;
iterable<Node https://www.w3.org/TR/dom/#node>;
};
根据WebIDL https://heycam.github.io/webidl/#idl-iterable, 这意味着
实现声明为可迭代的接口的对象
支持迭代以获得一系列值。
注意:在 ECMAScript 语言绑定中,接口是
iterable 将具有“entries”、“forEach”、“keys”、“values” 和@@迭代器 https://tc39.github.io/ecma262/#sec-well-known-symbols其上的属性接口原型对象 https://heycam.github.io/webidl/#dfn-interface-prototype-object.
因此,以下情况是可能的:
for (var el of document.querySelectorAll(selector)) ...
我注意到 HTMLCollections 似乎同样适用,无论是在 Firefox 还是 Chrome 上:
for (var el of document.getElementsByTagName(tag)) ...
事实上,我得到
HTMLCollection.prototype[Symbol.iterator] === [][Symbol.iterator]; // true
然而,HTML集合 https://www.w3.org/TR/dom/#interface-htmlcollection未定义为可迭代:
interface HTMLCollection {
readonly attribute unsigned long length https://www.w3.org/TR/dom/#dom-htmlcollection-length;
getter Element https://www.w3.org/TR/dom/#element? item https://www.w3.org/TR/dom/#dom-htmlcollection-item(unsigned long index);
getter Element https://www.w3.org/TR/dom/#element? namedItem https://www.w3.org/TR/dom/#dom-htmlcollection-nameditem(DOMString name);
};
我还检查了WHATWG DOM 规范 https://dom.spec.whatwg.org/#interface-htmlcollection而且它也不是可迭代的。
那么,这种行为是否规范呢?是HTMLCollection
应该有一个@@iterator
在原型中?