Comment corriger tableau indexOf () en JavaScript pour les navigateurs Internet Explorer

si vous avez travaillé avec JavaScript à n'importe quelle longueur, Vous êtes conscient Qu'Internet Explorer n'implémente pas la fonction ECMAScript pour Array.prototype.indexOf () [y compris Internet Explorer 8]. Ce n'est pas un gros problème, parce que vous pouvez étendre la fonctionnalité sur votre page avec le code suivant.

Array.prototype.indexOf = function(obj, start) {
     for (var i = (start || 0), j = this.length; i < j; i++) {
         if (this[i] === obj) { return i; }
     }
     return -1;
}

Quand dois-je mettre en œuvre ceci?

si je l'enroule sur toutes mes pages avec le chèque suivant, qui vérifie si le fonction prototype existe et si non, aller de l'avant et étendre le prototype réseau?

if (!Array.prototype.indexOf) {

    // Implement function here

}

ou est-ce que la vérification du navigateur et si C'est Internet Explorer alors juste l'implémenter?

//Pseudo-code

if (browser == IE Style Browser) {

     // Implement function here

}
295
demandé sur Peter Mortensen 2009-11-16 22:27:28

10 réponses

comme ça...

if (!Array.prototype.indexOf) {

}

Comme recommandé compatibilité par MDC .

en général, le code de détection du navigateur est un grand non-non.

213
répondu Josh Stodola 2009-11-16 19:30:22

alternativement, vous pouvez utiliser la fonction jQuery 1.2 inArray , qui devrait fonctionner entre les navigateurs:

jQuery.inArray( value, array [, fromIndex ] )
140
répondu Moses Lee 2013-01-10 16:16:25

le code complet serait alors ceci:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

pour une réponse et un code vraiment complet à cela ainsi que d'autres fonctions de tableau, consultez Stack Overflow question correction des fonctions de tableau JavaScript dans Internet Explorer (indexOf, forEach, etc.) .

77
répondu Luis Perez 2017-05-23 12:26:20

Le trait de soulignement.la bibliothèque js a une fonction indexOf que vous pouvez utiliser à la place:

_.indexOf([1, 2, 3], 2)
14
répondu scotta7exander 2012-10-18 20:04:32

vous devez vérifier si elle n'est pas définie en utilisant if (!Array.prototype.indexOf) .

aussi, votre mise en œuvre de indexOf n'est pas correcte. Vous devez utiliser === au lieu de == dans votre énoncé if (this[i] == obj) , sinon [4,"5"].indexOf(5) serait 1 selon votre implémentation, ce qui est incorrect.

je vous recommande d'utiliser la mise en œuvre sur MDC .

10
répondu Eli Grey 2009-11-17 20:59:40

il y a la solution officielle de Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

(function() {
    /**Array*/
    // Production steps of ECMA-262, Edition 5, 15.4.4.14
    // Reference: http://es5.github.io/#x15.4.4.14
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(searchElement, fromIndex) {
            var k;
            // 1. Let O be the result of calling ToObject passing
            //    the this value as the argument.
            if (null === this || undefined === this) {
                throw new TypeError('"this" is null or not defined');
            }
            var O = Object(this);
            // 2. Let lenValue be the result of calling the Get
            //    internal method of O with the argument "length".
            // 3. Let len be ToUint32(lenValue).
            var len = O.length >>> 0;
            // 4. If len is 0, return -1.
            if (len === 0) {
                return -1;
            }
            // 5. If argument fromIndex was passed let n be
            //    ToInteger(fromIndex); else let n be 0.
            var n = +fromIndex || 0;
            if (Math.abs(n) === Infinity) {
                n = 0;
            }
            // 6. If n >= len, return -1.
            if (n >= len) {
                return -1;
            }
            // 7. If n >= 0, then Let k be n.
            // 8. Else, n<0, Let k be len - abs(n).
            //    If k is less than 0, then let k be 0.
            k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
            // 9. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ToString(k).
                //   This is implicit for LHS operands of the in operator
                // b. Let kPresent be the result of calling the
                //    HasProperty internal method of O with argument Pk.
                //   This step can be combined with c
                // c. If kPresent is true, then
                //    i.  Let elementK be the result of calling the Get
                //        internal method of O with the argument ToString(k).
                //   ii.  Let same be the result of applying the
                //        Strict Equality Comparison Algorithm to
                //        searchElement and elementK.
                //  iii.  If same is true, return k.
                if (k in O && O[k] === searchElement) {
                    return k;
                }
                k++;
            }
            return -1;
        };
    }
})();
9
répondu Will V King 2015-03-12 06:20:06

je le recommande à tous ceux qui cherchent une fonctionnalité manquante:

http://code.google.com/p/ddr-ecma5 /

, Il apporte dans la plupart des disparus ecma5 de la fonctionnalité âgées browers :)

5
répondu Josh Mc 2012-06-07 23:55:31

C'était mon implémentation. Essentiellement, ajoutez ceci avant tous les autres scripts sur la page. i.e. dans votre master pour une solution globale pour Internet Explorer 8. J'ai également ajouté dans la fonction trim qui semble être utilisé dans beaucoup de cadres.

<!--[if lte IE 8]>
<script>
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(obj, start) {
            for (var i = (start || 0), j = this.length; i < j; i++) {
                if (this[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
    }

    if(typeof String.prototype.trim !== 'function') {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        };
    };
</script>
<![endif]-->
2
répondu Glennweb 2014-03-13 05:52:00

ça me va.

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/) {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)? Math.ceil(from) : Math.floor(from);
    if (from < 0)
    from += len;

    for (; from < len; from++) {
      if (from in this && this[from] === elt)
        return from;
    }
    return -1;
  };
}
2
répondu Allen Wong 2016-01-28 06:54:52

avec Underscore.js

var arr=['a','a1','b'] _.filter(arr, function(a){ return a.indexOf('a') > -1; })

1
répondu sri_bb 2015-01-21 12:33:53