2011-08-22 40 views

回答

64

Array.filter()不包括在IE,直到版本9

您可以使用它来实现它:

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; 
    }; 
} 

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

或者因为你使用jQuery,您可以首先将你的数组包装成一个jQuery对象:

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

过滤函数的参数是一个索引。为了得到实际的元素,你可以简单地使用'this'。 http://api.jquery.com/filter/ – Dennis

+2

谢谢!这工作完美。 –

+0

您也可以在函数中执行v,其中v是数组,而i是元素。 –

0

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

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

使用es5-shim,所以你可以在IE8中使用filter/indexOf!

Facebook的react.js也使用它。

<!--[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

相关问题