2009-09-07 5 views
0

Disons que je le tableau suivant en JavaScript:une suite de caractères à une valeur dans un tableau et renvoyer l'identifiant de cette valeur en JavaScript

var skins = new Array('Light', 'Medium', 'Dark'); 

Comment pourrais-je aller sur la vérification pour voir ce que ID dans ce array (0, 1 ou 2) a une valeur correspondante à une chaîne que je lui donne. Ainsi, par exemple, si je regarde une chaîne de « Medium », je serais retourné l'ID 1.

+0

Jetez un oeil à ce qui suit: http://stackoverflow.com/questions/1137436/useful-javascript-methods-that-extends-built -in-objets/1137481 # 1137481 – Canavar

Répondre

2

Vous pouvez utiliser Array.indexOf:

var index = skins.indexOf('Medium'); // 1 

Cette fonction a été introduite dans JavaScript 1.6, mais vous pouvez incluez-le pour la compatibilité avec les anciens navigateurs.

Voici l'algorithme utilisé par Firefox:

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; 
    }; 
} 
0
Array.prototype.lastIndex= function(what){ 
var L= this.length; 
while(L){ 
    if(this[--L]=== what) return L; 
} 
return -1; 
} 

Array.prototype.firstIndex= function(what){ 
var i=0, L= this.length; 
while(i<L){ 
    if(this[i]=== what) return i; 
    ++i; 
} 
return -1; 
} 
Questions connexes