HTMLCollection 和 NodeList 是可迭代的吗? [英] Are HTMLCollection and NodeList iterables?

查看:34
本文介绍了HTMLCollection 和 NodeList 是可迭代的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ES6 中,iterable 是一个允许 for 的对象... of,并有一个 Symbol.iterator 键.

In ES6, an iterable is an object that allows for... of, and has a Symbol.iterator key.

数组是可迭代的,集合和映射也是.问题是:HTMLCollectionNodeList 迭代?他们应该是吗?

Arrays are iterables, as are Sets and Maps. The question is: are HTMLCollection and NodeList iterables? Are they supposed to be?

MDN 文档似乎暗示 NodeList 是可迭代的.

MDN documentation seems to suggest a NodeList is an iterable.

for...of 循环将正确循环 NodeList 对象,在支持 for...of 的浏览器中(如 Firefox 13 及更高版本)

for...of loops will loop over NodeList objects correctly, in browsers that support for...of (like Firefox 13 and later)

这似乎证实了 Firefox 的行为.

This appears to corroborate Firefox's behaviour.

我在 Chrome 和 Firefox 中测试了以下代码,并惊讶地发现 Firefox 似乎认为它们是可迭代的,但 Chrome 没有.另外Firefox认为HTMLCollectionNodeList返回的迭代器是一回事.

I tested the following code in both Chrome and Firefox, and was surprised to find that Firefox seem to think they are iterables, but Chrome does not. In addition, Firefox thinks that the iterators returned by HTMLCollection and NodeList are one and the same.

var col = document.getElementsByClassName('test'); // Should get HTMLCollection of 2 elems
var nod = document.querySelectorAll('.test');      // Should get NodeList of 2 elems
var arr = [].slice.call(col);                      // Should get Array of 2 elems

console.log(col[Symbol.iterator]);    // Firefox: iterator function, Chrome: undefined
console.log(nod[Symbol.iterator]);    // Firefox: iterator function, Chrome: undefined
console.log(arr[Symbol.iterator]);    // Firefox & Chrome: iterator function
console.log(col[Symbol.iterator] === nod[Symbol.iterator]);  // Firefox: true
console.log(col[Symbol.iterator] === arr[Symbol.iterator]);  // Firefox: false

<div class="test">1</div>
<div class="test">2</div>

一件非常奇怪、令人困惑的事情:运行代码片段会产生与复制它并在 Firefox 中的实际文件/控制台中运行不同的结果(特别是最后的比较).对这里这种奇怪行为的任何启发也将不胜感激.

One really weird, confusing thing: running the code snippet produces a different result from copying it and running in an actual file/console in Firefox (particularly last comparison). Any enlightenment on this weird behaviour here would be appreciated too.

推荐答案

Symbol.iterator 支持 NodeListHTMLCollectionDOMTokenListDOMSettableTokenList讨论添加去年 WHATWG 的 DOM 规范.

Symbol.iterator support for NodeList, HTMLCollection, DOMTokenList, and DOMSettableTokenList was discussed and added to the WHATWG's DOM spec last year.

这篇关于HTMLCollection 和 NodeList 是可迭代的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆