SCRIPT438 Error in Internet Explorer 11

前端 未结 4 2074
野的像风
野的像风 2020-12-28 18:06

I\'ve been working on JavaScript lately, and everything was fine until I opened my page in IE11. as per Mozilla website .forEach is supported f

相关标签:
4条回答
  • 2020-12-28 18:19
    if (typeof Array.prototype.forEach != 'function') {
    Array.prototype.forEach = function (callback) {
        for (var i = 0; i < this.length; i++) {
            callback.apply(this, [this[i], i, this]);
        }
     };
    }
    
    if (window.NodeList && !NodeList.prototype.forEach) {
        NodeList.prototype.forEach = Array.prototype.forEach;
     }  
    
    0 讨论(0)
  • 2020-12-28 18:29

    To avoid changing the code for every forEach() call, here's a polyfill that worked for me. It's simple and recommended within https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach when running forEach() on a NodeList.

    if (window.NodeList && !NodeList.prototype.forEach) {
        NodeList.prototype.forEach = Array.prototype.forEach;
    }
    
    0 讨论(0)
  • 2020-12-28 18:34

    Finally mystery solved.

    Apparently, IE9 and above supports Array.forEach but not for NodeList, which querySelector returns. I tried Array.from() to no avail as it requires ES6 or use ES6-shim.

    All I had to do was to convert from nodeList to Array, and I did by this.

    Array.prototype.slice.call(document.querySelectorAll("nav a"), 0);
    

    as appeared in question In Javascript, what is the best way to convert a NodeList to an array

    0 讨论(0)
  • 2020-12-28 18:36

    I was doing so:

    Array.from(document.querySelectorAll(someElements))
    

    The asnwer for me was simply that:

    if (window.NodeList && !NodeList.prototype.forEach) {
       NodeList.prototype.forEach = Array.prototype.forEach;
    }
    

    Making sure that forEach also exists in Nodelist.

    0 讨论(0)
提交回复
热议问题