IE supports forEach(…) when invoked fromthe console but not when called from the code

旧时模样 提交于 2019-12-01 02:20:47

问题


I'm running this snippet the console. In IE it produces the output just as expected. Running the same in Cr and FF for reference confirms the congruence of behavior.

["a", "b"].forEach(function(element) {
  console.log(element);
});

However, when running the following script, I'm getting errors telling me that the object hasn't forEach(...) declared on it. The issue occurs in IE but not in Cr nor FF.

var menus = document.querySelectorAll("ul.application>li>a");
menus.forEach(function(element) { ... }

I've checked that the variable menus is declared and that picking it's elements produces what I would expect, i.e. menus[0] exists and is a tag. It looks a bit differently in IE compared to the others but it might be just the different rendition.

I've been blessed working with Cr and FF so my experience in dealing with IE is limited. Googling didn't give me much wisdom, neither.

How do I troubleshoot it further?


回答1:


Basically document.querySelectorAll would return a nodeList an array like object not an array. You have to convert it to an array before invoking array functions over that.

var menus = document.querySelectorAll("ul.application>li>a");
menus = [].slice.call(menus);
menus.forEach(function(element) { ... });

If your environment supports ES6 then you can use Array.from()

var menus = document.querySelectorAll("ul.application>li>a");
menus = Array.from(menus);
menus.forEach(function(element) { ... });



回答2:


It is not a problem of the browser, it is more like you get an array like object, with querySelectorAll. It returns a NodeList, which is iterable, but not directly with array methods.

But you can borrow the method from Array.prototype, like this one

Array.prototype.forEach.call(menu, function(element) { /* ... */ });

If you like to get first a real array, you could convert it with

array = Array.apply(null, menu);



回答3:


Little late, but it might be useful if someone has the same problem and doesn't want/can't replace all forEach methods with [].forEach.call(elements, fn(el)). Here is polyfill that works for ie11

if (! Object.getOwnPropertyDescriptor(NodeList.prototype, 'forEach')) {
    Object.defineProperty(NodeList.prototype, 'forEach', Object.getOwnPropertyDescriptor(Array.prototype, 'forEach'));
}


来源:https://stackoverflow.com/questions/41142932/ie-supports-foreach-when-invoked-fromthe-console-but-not-when-called-from-t

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