为什么.filter()在Internet Explorer 8中不起作用?

Jac*_*k B 26 javascript jquery internet-explorer

这是一行:

songs = songs.filter(function (el) {
  return el.album==album;
});  
Run Code Online (Sandbox Code Playgroud)

这是错误:

Object不支持此属性或方法

这在Chrome中100%正常工作.这是怎么回事?

Pau*_*aul 69

Array.filter() 在版本9之前不包含在IE中.

您可以使用它来实现它:

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;
  };
}
Run Code Online (Sandbox Code Playgroud)

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

或者,因为您正在使用jQuery,所以您可以先将数组包装到jQuery对象中:

songs = $(songs).filter(function(){
  return this.album==album;
}); 
Run Code Online (Sandbox Code Playgroud)