问题描述
在ES6中,是一个允许 for ... of
,并具有Symbol.iterator键。
数组是迭代,集合和地图也是。问题是:和 iterables?他们应该是吗?
MDN文档似乎建议一个 NodeList
是一个可迭代的。
这似乎证实了Firefox的行为。
我在Chrome和Firefox中测试了以下代码,并惊讶地发现Firefox似乎认为它们是可迭代的,但Chrome并没有。另外,Firefox认为由 HTMLCollection
和 NodeList
返回的迭代器是一样的。
var col = document.getElementsByClassName('test'); //应该获得HTMLCollection 2 elemsvar nod = document.querySelectorAll('。test'); //应该得到NodeList的2 elemsvar arr = [] .slice.call(col); //应该获得2的数组elemsconsole.log(col [Symbol.iterator]); // Firefox:iterator函数,Chrome:undefinedconsole.log(nod [Symbol.iterator]); // Firefox:iterator function,Chrome:undefinedconsole.log(arr [Symbol.iterator]); // Firefox& Chrome:iterator functionconsole.log(col [Symbol.iterator] === nod [Symbol.iterator]); // Firefox:trueconsole.log(col [Symbol.iterator] === arr [Symbol.iterator]); // Firefox:false
< div class =test > 1< / div>< div class =test> 2< / div>
b
$ b
一个非常奇怪的,令人困惑的事情:运行代码段会产生不同的结果,复制它并在Firefox的实际文件/控制台中运行(特别是最后的比较) 。对这个奇怪的行为的任何启发也将不胜感激。
Symbol.iterator
支持 NodeList
, HTMLCollection
, DOMTokenList
和 DOMSettableTokenList
是和到去年。
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 HTMLCollection and NodeList iterables? Are they supposed to be?
MDN documentation seems to suggest a NodeList
is an iterable.
This appears to corroborate Firefox's behaviour.
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>
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
support for NodeList
, HTMLCollection
, DOMTokenList
, and DOMSettableTokenList
was discussed and added to the WHATWG's DOM spec last year.
这篇关于HTMLCollection和NodeList是否可以迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!