2011-08-22 15 views
26

Questa è la linea:Perché not .filter() funziona in Internet Explorer 8?

songs = songs.filter(function (el) { 
    return el.album==album; 
}); 

Questo è l'errore:

Object doesn't support this property or method

Questo funziona al 100% bene in Chrome. Cosa sta succedendo?

+0

ho inviato la mia risposta prima ho visto Paolo. Le canzoni sono un array o un oggetto jQuery? – Dennis

risposta

64

Array.filter() non è incluso in Internet Explorer fino alla versione 9.

È possibile utilizzare questo per la sua attuazione:

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

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

, ovvero dal momento che si sta utilizzando jQuery, è possibile per prima cosa avvolgere la matrice in un oggetto jQuery:

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

L'argomento per la funzione filtro è un indice. Per ottenere l'elemento reale, puoi semplicemente usare 'this'. http://api.jquery.com/filter/ – Dennis

+2

Grazie! Questo ha funzionato perfettamente. –

+0

Si potrebbe anche fare i, v nella funzione, dove v è la matrice e i è l'elemento. –

0

L'uso della funzione attr() funziona?

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

Usa es5-shim, quindi puoi usare filter/indexOf in IE8!

react.js di Facebook utilizza anche quello.

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

Problemi correlati