Reputation: 581
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 ?
Upvotes: 0
Views: 1987
Reputation: 1903
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>
Upvotes: 4
Reputation: 2696
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]
Upvotes: 2