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?
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?
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())];
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.
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.
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!