Using Images In Array/Object

Good afternoon.

I’m creating a random fruit generator to help me decide what fruits to put in my shopping basket.

So far so good in terms of using an array and inserting the name of the fruit, but I want a picture too.

And I have no idea how to use images in an array - or even if you can. Google searches have not helped me.

I am also assuming I will need an object instead of an array too? To display both the image and name of the fruit.

Can anyone point me in the right direction?

Thanks
James

Here’s some strategy that might work for you: why don’t you store all the images in a folder, and have a multi-dimensional array containing both the name of the fruit and the url of the image of that fruit -
so the array would be [[‘fruit1Name’, ‘fruit1ImageUrl’], [‘fruit2Name’, ‘fruit2ImageUrl’], [‘fruit3Name’, ‘fruit3ImageUrl’], [‘fruit4Name’, 'fruit4ImageUrl] … etc

That would be one way, although I’d prefer to use objects as I think it makes the code more readable and makes it easier to add more properties at a later date.

You could set up the array something like this:

var fruitsArray = [
  { name: 'Banana', image: 'banana.jpg' }, 
  { name: 'Apple', image: 'apple.jpg' }, 
  { name: 'Orange', image: 'orange.jpg' }
];

and then when updating the page with the random fruits:

for (var i = 0; i < boldStuffs.length; i += 1) {
    var fruit = getRandomItem(fruitsArray);
    boldStuffs[i].innerHTML = fruit.name + '<img src="'+fruit.image+'">';
}

That is amazing, thanks! Do you think I’d be better off trying to set image width/height with JavaScript?

If you’re intending to use images that are already the right size, then I wouldn’t bother. Otherwise, it’s probably best to set the size via CSS.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.