简体   繁体   中英

Why won't .filter() work in Internet Explorer 8?

This is the line:

songs = songs.filter(function (el) {
  return el.album==album;
});  

This is the error:

Object doesn't support this property or method

This Works 100% fine in Chrome. What's going on?

Array.filter() isn't included in IE until version 9.

You could use this to implement it:

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter

Or since you are using jQuery, you can wrap your array into a jQuery object first:

songs = $(songs).filter(function(){
  return this.album==album;
}); 

Use es5-shim, so you can use filter/indexOf in IE8!

Facebook's react.js using that too.

  <!--[if lte IE 8]>
  <script type="text/javascript" src="/react/js/html5shiv.min.js"></script>
  <script type="text/javascript" src="/react/js/es5-shim.min.js"></script>
  <script type="text/javascript" src="/react/js/es5-sham.min.js"></script>
  <![endif]-->

https://github.com/es-shims/es5-shim

Does using the attr() function work?

songs = songs.filter(function (index) {
    return $(this).attr("album") == album;
});  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM