Edge 15 throws error when using 'for … of' on a NodeList

与世无争的帅哥 提交于 2021-02-10 03:59:26

问题


When looking at the ECMAScript compatibility table, it says that Edge 15 and Edge 16 support for ... of loops.

However, when I run this code:

const list = document.querySelectorAll('[data-test]');
console.log(list);

for (const item of list) {
  console.log(item);
}
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>

It works in Chrome and Firefox, but not in Edge. Instead it says:

Object doesn't support property or method 'Symbol.iterator'.

As I understand it, NodeList actually should support it, right?

Here's a fildde to try it yourself: Test it online

Can somebody explain the problem or the mistake here?


回答1:


Edge does support for... of.

It would seem that it doesn't support iterators on NodeLists. Not all array-like objects support iterators and I'm not sure whether there is any standard saying that NodeLists have to.

In any case, it's easy enough to get for ... of to work with them:

const list = document.querySelectorAll('[data-test]');

for (const item of Array.from(list)) {
	console.log(item);
}
<div data-test>a</div>
<div data-test>b</div>
<div data-test>c</div>
<div data-test>d</div>
<div data-test>e</div>



回答2:


If for..of is supported but Edge 15 forgot to add the behavior to NodeList, you could polyfill it yourself with very little code:

NodeList.prototype[Symbol.iterator] = function* () {
    for(var i = 0; i < this.length ; i++) {
        yield this[i]
    }
}

To answer the other question (is it defined as iterable in the spec?) the answer is yes:

The DOM spec defines NodeList as:

interface NodeList {
  getter Node? item(unsigned long index);
  readonly attribute unsigned long length;
  iterable<Node>;
};

Note the third property, iterable<Node>;. Looking it up in the WebIDL spec:

In the ECMAScript language binding, an interface that is iterable will have “entries”, “forEach”, “keys”, “values” and @@iterator properties on its interface prototype object.

It seems that Edge doesn't implement any of that.



来源:https://stackoverflow.com/questions/47287344/edge-15-throws-error-when-using-for-of-on-a-nodelist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!