Javascript - indexOf sugli array
Uno dei metodi introdotti in Firefox con Javascript 1.5 è indexOf.
Ovviamente non intendo l’indexOf delle stringhe:
alert("ciao".indexOf("a")): //Restituisce 2 Bensì il "nuovo" metodo applicabile agli array:
alert(["ciao", "hello"].indexOf("hello")); //Restituisce 1
il quale restituisce in che posizione si trova l’elemento passato come argomento.
La documentazione ufficiale suggerisce di usare questa funzione per rendere il metodo compatibile anche con gli altri browser: if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
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;
};
}