Thursday, May 23, 2013

How to choose a random value from an array using JavaScript?

Use the following pseudo code to alert a random values from given array using javascript.
var item_array = [1, 3, 4, 5];
var random_item = item_array[Math.floor(Math.random() * item_array.length)];
alert(random_item);

Explanation:
Create an array of your choice, then pick one element from the array. You do this by choosing a random number using Math.random(), which gives you a result greater than or equal to 0 and less than 1. Multiply by the length of your array, and take the floor (that is, take just the integer part, dropping off any decimal points), so you will have a number from 0 to one less than the length of your array (which will thus be a valid index into your array). Use that result to pick an element from your array.

Source: http://stackoverflow.com/questions/5708784/how-do-i-choose-a-random-value-from-an-array-with-javascript

No comments:

Post a Comment