No hay ningún problema en hacer:
Código PHP:
var miArray = new Array();
miArray["frutas"] = "peras, plátanos y limones";
miArray["sesenta"] = 60;
miArray["dospordos"] = 4
miArray["2x2"] = 4;
miArray["una frase larga"] = "otra frase larga";
miArray[0] = "hola";
miArray[1] = "que tal";
miArray[2] = "estamos";
document.write( miArray["frutas"] +"<br/>");
document.write( miArray["sesenta"] +"<br/>");
document.write( miArray["dospordos"] +"<br/>" );
document.write( miArray["2x2"] +"<br/>");
document.write( miArray["una frase larga"] +"<br/>");
document.write( miArray["noexisto"] +"<br/>");
document.write("--------------------------<br/>");
for(var i in miArray) {
document.write(i+" --> "+miArray[i] +"<br/>");
}
document.write("--------------------------<br/>");
function existeClave(lista,clave) {
return (clave in lista);
}
document.write("¿Existe la clave 'dospordos'? "+existeClave(miArray, 'dospordos') +"<br/>");
document.write("¿Existe la clave 'sesenta'? "+existeClave(miArray, 'sesenta') +"<br/>");
document.write("¿Existe la clave 'no existo'? "+existeClave(miArray, 'no existo') +"<br/>");
document.write("--------------------------<br/>");
// Miramos si existe el valor en el array asociativo. Devuelve la clave si sí existe, false si no existe.
// No devuelve varias claves si hay valores iguales en el array
// No compatible con array que tenga como clave false, no notaremos la diferencia si existe el valor o si no.
function existeValor(lista, valor){
for(var i in lista)
if (lista[i] === valor)
return i;
return false;
}
document.write("¿Existe el valor 'otra frase larga'? "+existeValor(miArray, 'otra frase larga') +"<br/>");
document.write("¿Existe el valor '4'? "+existeValor(miArray, 4) +"<br/>");
document.write("¿Existe el valor 'no existo'? "+existeValor(miArray, 'no existo') +"<br/>");
document.write("--------------------------<br/>");
Como ves la función
existeClave() será muy rápida y la función
existeValor() será muy lenta, pero las dos funcionan satisfactoriamente. Fíjate en la forma de recorrer el array, y que la propiedad
length de miArray contendrá
3, que son los índices numéricos definidos.
Un saludo y espero que con esto ver la solución sea sencillo.
Byes.