简体   繁体   中英

How do I retrieve a random object from an array of objects ? Javascript

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 ?

 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> 

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM