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 ?

6
  • 1
    Math.random() + size of array (after jsonparsing) + use the result as index = your answer Commented Apr 28, 2015 at 21:25
  • 1
    You don't have an array. You have JSON Object. Commented Apr 28, 2015 at 21:25
  • try this var item = imagesArray [Math.floor(Math.random()*imagesArray .length)]; Commented Apr 28, 2015 at 21:26
  • use the random array thingie on Object.keys(obj), then pull that key. Commented Apr 28, 2015 at 21:26
  • wow, quick responses, thanks guys will get right on it :) Commented Apr 28, 2015 at 21:27

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

great, nice and simple and with a runnable code snippet :) Thanks, will accept your answer when i can :))
@Kostas Nice, its simple way but sometimes its giving same two times I want to avoid this how I can do that
@AhteshamShah I made a fiddle for not giving you the same result. 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.
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.