2011-08-22 17 views

Odpowiedz

64

Array.filter() nie jest wliczone w IE aż do wersji 9.

Można to wykorzystać do jego realizacji:

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

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

Albo skoro używasz jQuery, można najpierw zapakuj tablicę do obiektu jQuery:

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

Argumentem funkcji filtru jest indeks. Aby uzyskać rzeczywisty element, możesz po prostu użyć 'this'. http://api.jquery.com/filter/ – Dennis

+2

Dziękujemy! To działało idealnie. –

+0

Można również wykonać i, v w funkcji, gdzie v jest tablicą, a ja jest elementem. –

0

Czy działa funkcja attr()?

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

Użyj es5-shim, więc możesz użyć filtra/indexOf w IE8!

Facebook react.js również tego używa.

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

Powiązane problemy