views:

376

answers:

4

Learning JS this week.

Is it possible to use Math.random to return a random value in an array? Does that value be a string and still work?

+5  A: 

You can take the floating point number (between 0 and 1, non-inclusive) and convert it to an index to the array (integer between 0 and length of the array - 1). For example:

var a = ['a', 'b', 'c', 'd', 'e', 'f'];
var randomValue = a[Math.floor(a.length * Math.random())];
Lukáš Lalinský
Thanks! I'm using rather longer statement strings in each array value. Is there a way to syntactically write this so it's not just one very large line?
Francis
It doesn't matter how do you construct the array. The important part is `floor(length_of_the_array * random_value_between_0_and_1)`.
Lukáš Lalinský
A: 

Read this:

var arr = [1, 2, 3, 4, 5, 6];
var r = arr[Math.floor(Math.random()*a.length)]; // r will store a value from a pseudo-random position at arr.
Rodrigo
Math.round(Math.random()*a.length) can return a number that is equal to a.length, which is not a valid index to the array.
Lukáš Lalinský
Thanks, it was fixed.
Rodrigo
+1  A: 

Yes, this is indeed possible. Here's some example code:

<script>
    var arr = new Array('a', 'b', 'c', 'd', 'e');
    document.write("Test " + arr[Math.floor(Math.random() * ((arr.length - 1) - 0 + 1))]);
</script>

Note that Math.floor should be used instead of Math.round, in order to get a uniform number distribution.

Jez
A: 

Thanks for all your help.

//My array was setup as such.
var arr = New Array();
arr[0]="Long string for value.";
arr[1]="Another long string.";
//etc...

With your help, and since I know the exact number of values in my array (2), I just did:

var randomVariable = arr[Math.floor(2*Math.random())]

Then output randomVariable how I wish.

Thanks!

Francis
You should use `arr.length`, not `2`.
Lukáš Lalinský