PROBLEM
How to iterate through an array of objects?
PEN
Codepen: penHere
CODE
I declared this global const:
const items=[
{
name: "axe",
image: "https://image.ibb.co/cjtHPe/if_weapon_04_707486.png",
hit: 3
},
{
name: "redPotion",
image: "https://image.ibb.co/gTmU4e/if_18_Harry_Potter_Colour_Potion_Bottle_2730331.png",
health: 40
},
];
with this function I gave to characters and items random coordinates where to spawn
function placeCharAndItem(char, items){
let coord = randomCoord();
let toCheck = mapA[coord.row][coord.cell];
let check = toCheck.search('nonWalkable');
while(check != -1){
coord = randomCoord();
toCheck = mapA[coord.row][coord.cell];
check= toCheck.search('nonWalkable');
};
place(coord, char);
placeItem(coord, items);
};
and with the function below the items should be spawn in the map:
function placeItem(coord, items){
items.forEach(function(obj){
console.log(items.name);
coord=randomCoord();
var charImage = $("<img>").attr("src", items.image).addClass('items');
var row = $($("#tableGame tr")[coord.row]);
var cell = $($("td", row)[coord.cell]);
var tile = $(".tile", cell); tile.prepend(charImage);
})
};
The main problem is that the arrays is iterating(i think) but everytime it gives me " undefined" instead of give me the proper link to the images.
TASK
I've to show the image of these items in a table
Considerations
I read several of your answers about this topic in Stack Overflow, they recommended to use forEach
or and old-fashon for
loops, I hope I'm correct about this, but if I'm in the wrong way any kind of correction would be really appreciated.