Javascript: Arrays, getting a random element from an Array in Javascript (a bit like PHP shuffle)

Building out the RPG game, I have a shop that is situated in a room that only sells one item and I wanted that item to be taken from random from a list of possible things it could sell.

So i thought the simplest way was to have an array of all the things it could sell and then pick one out from random.
Unfortunately, Javascript doesn’t have the lovely PHP shuffle() function which returns the array with its elements ‘shuffled’ which actually I don’t usually want – I usually just want one at random.

So here’s what I did to achieve the same thing

sprite_heroes = new Array('mario','sonic','turrican','tron','rockford','pitfall harry');

random_hero = sprite_heroes[parseInt(Math.random()*sprite_heroes.length)];

// hopefully it's self-explanatory
// but if not, all I'm doing is using the Math.random() method and the array's length to generate a random number
// between 0 and the number of items in the array

// or as a function

random_hero = lucky_dip(sprite_heroes);

function lucky_dip(your_array) {
return your_array[parseInt(Math.random()*your_array.length)];

// or as a prototype on an array
Array.prototype.lucky_dip = function() {
return this[parseInt(Math.random()*this.length)];

Leave a Reply