Is there a simple way to make a random selection f

2019-01-24 02:10发布

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>

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-24 02:53

It's easy in Python.

>>> import random
>>> random.choice(['red','green','blue'])
'green'

The reason the code you're looking at is so common is that typically, when you're talking about a random variable in statistics, it has a range of [0,1). Think of it as a percent, if you'd like. To make this percent suitable for choosing a random element, you multiply it by the range, allowing the new value to be between [0,RANGE). The Math.floor() makes certain that the number is an integer, since decimals don't make sense when used as indices in an array.

You could easily write a similar function in Javascript using your code, and I'm sure there are plenty of JS utility libraries that include one. Something like

function choose(choices) {
  var index = Math.floor(Math.random() * choices.length);
  return choices[index];
}

Then you can simply write choose(answers) to get a random color.

查看更多
叼着烟拽天下
3楼-- · 2019-01-24 02:55

In Python it is...

import random

a=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'etc.']
print random.choice(a)
查看更多
登录 后发表回答