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


使用attr()函数是否工作?

songs = songs.filter(function (index) {
    return $(this).attr("album") == album;
});  
链接地址: http://www.djcxy.com/p/55324.html

上一篇: 搜索嵌套对象的数组,如果在子中找到值,则返回父对象

下一篇: 为什么.filter()不能在Internet Explorer 8中工作?