I'm reading a beginner's JavaScript book with some code that compares the coder's input (var answer) to a randomly chosen string from an array (answers). It's a guessing game.
I am confused about the way a string is chosen randomly. The code appears to be multiplying the Math.random function by the answers array and its length property. Checking around, this appears to be the standard way to make a random selection from an array? Why would you use a math operator, the *, to multiply... out... a random string based on an array's length? Isn't the length technically just 3 strings? I just feel like it should be something simple like index = answers.random. Does that exist in JS or another language?
<script>
var guess = "red";
var answer = null;
var answers = [ "red",
"green",
"blue"];
var index = Math.floor(Math.random() * answers.length);
if (guess == answers[index]) {
answer = "Yes! I was thinking " + answers[index];
} else {
answer = "No. I was thinking " + answers[index];
}
alert(answer);
</script>
Math.random
gives you a random number between 0 and 1.Multiplying this value by the length of your array will give you a number strictly less than the length of your array.
Calling
Math.floor
on that will truncate the decimal, and give you a random number within the bounds of your arrayHere you go
Math.random
and similar functions usually return a number between 0 and 1. As such, if you multiply the random number by your highest possible valueN
, you'll end up with a random number between 0 andN
.JavaScript
No. Vanilla JS does not provide any method like the following. You have to calculate, unfortunately.
Try it out here.
But, if you are using lodash, the above method is already covered.
Try it out here.
Python
Try it out here.
Ruby
using a single data type,
using multiple data types,
Try it out here.
Updated: JavaScript example added.
Popular Underscore javascript library provides function for this, which can be used similar to python's random.choice :
http://underscorejs.org/#sample