Javascript - forEach() 循环在 IE11 上不工作

Javascript - forEach() loops not working on IE11

forEach 循环应该在 IE11 和显示中工作

Object doesn't support property or method 'forEach'.

它应该可以工作,因为它是一个 ECMAScript-5 函数并且 IE11 supports it

但是,我这里的代码不起作用:

var alltable = document.querySelectorAll('*[id^="table_"]'); //Select all elements with the id starting by "table_"
    alltable.forEach(function(element) {
                // Do some code
                });

知道为什么吗?

我自己,

forEach() 实际上适用于 IE11,请注意如何调用它。

querySelectorAll() 是 return 一个 NodeList 的方法。 在 Internet Explorer 上,foreach() 仅适用于 Array 对象。 (它与 ES6 的 NodeList 一起工作,not supported by IE11).

要解决这个问题,有些人会建议使用 polyfill,它可能会很好用,但您也可以使用 slice.call() 方法将 NodeList 简单地转换为数组:(Explained here)

var alltable = document.querySelectorAll('*[id^="table_"]'); //Select all elements with the id starting by "table_"
var alltableArray= Array.prototype.slice.call(alltable);
    alltableArray.forEach(function(element) {
                // Do some code
                });

或:

var alltable = Array.prototype.slice.call(document.querySelectorAll('*[id^="table_"]')); //Select all elements with the id starting by "table_"
    alltable.forEach(function(element) {
                // Do some code
                });

总结一下: 确保你在 Array 对象上使用它而不是 NodeList。

希望能帮到别人。