0

I have this bit of code that adds an image to the 'imageContainer'

$('.imageContainer').prepend('<img id="xboxLogo" src="images/xboxLogo.png"/>')

I have this array of objects :

var imagesArray = { 
    xboxLogo : {
        id : 'xboxLogo';
        src: "images/xboxLogo.png";     
    },
    playStatLogo : {
        id : 'playStatLogo';
        src: "images/playStatLogo.png"; 
    },
    wiiLogo : {
        id : 'wiiLogo';
        src: "images/wiiLogo.png";  
    }
    }

What I want to do is have a function that I call which adds the image to the 'imageContainer' but I want the image to be randomly picked from the 'imagesArray'. How do i randomly get one of the 3 (xbox,playStation,wii) images and then retrieve their attributes so I can use them to create the images ?

AJ_91
  • 581
  • 4
  • 16

2 Answers2

4

var imagesArray = [
  {
    id: 'xboxLogo',
    src: "images/xboxLogo.png"
  },
  {
    id: 'playStatLogo',
    src: "images/playStatLogo.png"
  },
  {
    id: 'wiiLogo',
    src: "images/wiiLogo.png"
  }
];

$('button').click(function() {
  var randomImage = imagesArray[Math.floor(Math.random() * imagesArray.length)];
  $('p').text(randomImage.src);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p></p>

<button>pick random</button>
Kostas
  • 1,903
  • 1
  • 16
  • 22
  • great, nice and simple and with a runnable code snippet :) Thanks, will accept your answer when i can :)) – AJ_91 Apr 28 '15 at 21:31
  • @Kostas Nice, its simple way but sometimes its giving same two times I want to avoid this how I can do that – Ahtesham Shah Oct 04 '19 at 07:34
  • @AhteshamShah I made a fiddle for not giving you the same result. https://jsfiddle.net/br3z1t8w/1/ . The idea is to subtract the item from the array each time and return the array back when it's empty. – Kostas Oct 06 '19 at 00:21
2

Generate a random number that will be the index of the image you want.

var keys = Object.keys(imagesArray);
var n = keys.length;
var index = Math.floor(Math.random() * n);
var randomKey = keys[index]
var image = imagesArray[randomKey]
Transcendence
  • 2,616
  • 3
  • 21
  • 31