Method for does not show images in array

2

Query, why when showing images with this for method, shows only the array " Collection.push " but I can not display strong> the array " images " with the same method for changing the for parameter (var objects of collection ) for the for (var objects of images )?.

I do not throw any errors in console but it shows nothing once I change images for collection .

Greetings and thank you very much!

var imagenes=[];
imagenes["Cauchin"]="vaca.png";
imagenes["Pocacho"]="pollo.png";
imagenes["Tocinaurio"]="cerdo.png";

var coleccion=[];
coleccion.push(new Pakiman("Pocacho",100,30));
coleccion.push(new Pakiman("Tocinaurio",150,70));
coleccion.push(new Pakiman("Cauchin",50,40));

for (var objetos of coleccion)
{
console.log(objetos);
objetos.mostrar();
}
 class Pakiman
{
constructor(n,v,a)
{
    this.imagen= new Image();
    this.nombre=n;
    this.vida=v;
    this.ataque=a;
    this.imagen.src=imagenes[this.nombre];
}
hablar()
{
    document.writeln(this.nombre+" <strong>dice</strong>: 
"+this.nombre+"..."+this.nombre+"<br/>")
}
mostrar()
{
    document.body.appendChild(this.imagen);
    document.writeln("<br/>"+"<strong>Nombre: </strong>"+this.nombre+" 
<br/>"+"<strong>Vida: </strong>"+this.vida+"<br/>"+"<strong>Ataque: 
</strong>"+this.ataque+"<br/>");
}
}

With the parameter     for (var objects of collection )

with the parameter     for (var objects of images )

    
asked by Ketchup786 26.09.2018 в 22:21
source

2 answers

1

The error you have is that the array images you want to place it as an associative array, that is, an array whose indexes are not numeric but text strings, keys. If you want to make an associative array you have to make an array type json as I will show you next:

var imagenes=[];
imagenes["Cauchin"]="vaca.png";
imagenes["Pocacho"]="pollo.png";
imagenes["Tocinaurio"]="cerdo.png";

console.log(imagenes);

var imagenes = [];
imagenes.push("vaca.png");
imagenes.push("pollo.png");
imagenes.push("cerdo.png");

console.log(imagenes);

var imagenes = [{Cauchin: "vaca.png"},{Pocacho: "pollo.png"},{Tocinaurio: "cerdo.png"}];

console.log(imagenes);

If you look at the first one, it's how you wanted to do it, the second is how it should work and the third is how you really want it where you use {} keys to generate the array of key elements: value .

    
answered by 26.09.2018 / 22:54
source
0

In the case of the "images" arrangement you are treating the arrangement as an object. The image arrangement in this case has length 0 and has the 3 elements as properties of the object images. to go through the properties of the object you can do it with a 'for in'

for (var propiedad in imagenes)
{
    console.log(propiedad);
    console.log(imagenes[propiedad]);
}
    
answered by 26.09.2018 в 22:53