2011-08-22 41 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

相關問題