var arr = ['test', 'hello'];Opération de tableau Javascript
Y at-il un appel natif javascript pour obtenir l'indice d'une certaine valeur («bonjour») dans un tableau?
var arr = ['test', 'hello'];Opération de tableau Javascript
Y at-il un appel natif javascript pour obtenir l'indice d'une certaine valeur («bonjour») dans un tableau?
javascript 1.6+ vous pouvez utiliser .indexOf()
:
var index = arr.indexOf('hello');
Dans les versions précédentes, vous devriez juste faire une boucle à travers le réseau vous .
Fait intéressant, alert([].indexOf)
Chrome vous donne la mise en œuvre:
function indexOf(element, index) {
var length = this.length;
if (index == null) {
index = 0;
} else {
index = (_IsSmi(IS_VAR(index)) ? index : ToInteger(index));
if (index < 0) index = length + index;
if (index < 0) index = 0;
}
for (var i = index; i < length; i++) {
var current = this[i];
if (!(typeof(current) === 'undefined') || i in this) {
if (current === element) return i;
}
}
return -1;
}
Ne me demandez pas ce que _IsSmi(IS_VAR(index))
donc bien des ...
arr.indexOf("hello");
La méthode indexOf
est pas pris en charge dans tous les navigateurs (il a été ajouté en JavaScript 1.6), mais vous pouvez utiliser le code suivant pour le faire fonctionner dans ceux qui ne le font pas (code de l'MDC page for indexOf
):
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;
};
}
arr.indexOf('hello');
Je ne sais pas si cela fonctionne sur IE cependant (cela fonctionne sûrement sur Firefox et Webkit).
:-D
Je ne sais vraiment pas pourquoi je reçois le vote. La réponse n'est pas très différente des autres (sûrement pas faux). – NawaMan
où voir ma version javascript? – omg
la meilleure chose à faire est de voir si elle est supportée - if (typeof [] .indexOf == 'undefined') {vous ne l'avez pas} – Greg
Il est suppored, mais ne sait pas encore la version javascript :( – omg