Reputation:
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?
Upvotes: 9
Views: 44695
Reputation: 83
Yeah it is very possible to do what you're asking
const diceRoll = Array.from({ length: 100 }, (_, i) => {
return i + 1;
});
console.log(Math.random() * diceRoll.length);
The code there, why it works is that Math.random returns a random number between 0 and whatever value we set and the value we set here is diceRoll.length which is 100 so it will return a random value between 0 and 99
console.log(Math.random() * diceRoll.length + 1);
will make it return random value between 0 and 100
Upvotes: 0
Reputation: 1
You can use this:
var array = [];
for(i = 0; i < 6; i++) {
array[i] = Math.floor( Math.random() * 60 );
}
if you need a number between 1 and 100, just change Math.random() * 60 to Math.random() * 100.
Upvotes: 0
Reputation:
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!
Upvotes: 1
Reputation: 4395
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.
Upvotes: 3
Reputation: 29993
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.
Upvotes: 3
Reputation: 41306
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())];
Upvotes: 27