DOM4使 NodeList可迭代:
interface <i>NodeList</i> {
getter <a rel="noreferrer" href="https://www.w3.org/TR/dom/#node">Node</a>? <a rel="noreferrer" href="https://www.w3.org/TR/dom/#dom-nodelist-item">item</a>(unsigned long <i>index</i>);
readonly attribute unsigned long <a rel="noreferrer" href="https://www.w3.org/TR/dom/#dom-nodelist-length">length</a>;
iterable<<a rel="noreferrer" href="https://www.w3.org/TR/dom/#node">Node</a>>;
};
根据 WebIDL,这意味着:
实现声明为可迭代的接口的对象支持被迭代以获取一系列值。
注意:在 ECMAScript 语言绑定中,一个可迭代的接口将在其接口原型对象上具有“entries”、“forEach”、“keys”、“values”和 @@iterator 属性。
因此,以下操作是可能的:
for (var el of document.querySelectorAll(selector)) ...
我注意到同样适用于HTML集合,在Firefox和Chrome上都是如此:
for (var el of document.getElementsByTagName(tag)) ...
事实上,我得到
HTMLCollection.prototype[Symbol.iterator] === [][Symbol.iterator]; // true
然而,HTMLCollection 并未被定义为可迭代对象:
interface <i>HTMLCollection</i> {
readonly attribute unsigned long <a rel="noreferrer" href="https://www.w3.org/TR/dom/#dom-htmlcollection-length">length</a>;
getter <a rel="noreferrer" href="https://www.w3.org/TR/dom/#element">Element</a>? <a rel="noreferrer" href="https://www.w3.org/TR/dom/#dom-htmlcollection-item">item</a>(unsigned long <i>index</i>);
getter <a rel="noreferrer" href="https://www.w3.org/TR/dom/#element">Element</a>? <a rel="noreferrer" href="https://www.w3.org/TR/dom/#dom-htmlcollection-nameditem">namedItem</a>(DOMString <i>name</i>);
};
我还查看了WHATWG DOM规范,它也不可迭代。那么,这种行为是标准的还是不标准的?
HTMLCollection
应该在原型中有一个@@iterator
吗?