有没有一种简单的方法可以在JavaScript或任何其他编程语言中从数组中进行随机选择? [英] Is there a simple way to make a random selection from an array in JavaScript or any other programming language?

查看:191
本文介绍了有没有一种简单的方法可以在JavaScript或任何其他编程语言中从数组中进行随机选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读初学者的JavaScript书籍,其中包含一些代码,用于将编码器的输入(var answer)与从数组中随机选择的字符串(答案)进行比较。这是一个猜谜游戏。

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.

我对随机选择字符串的方式感到困惑。代码似乎是将Math.random函数乘以answers数组及其length属性。检查周围,这似乎是从数组中随机选择的标准方法?你为什么要使用数学运算符*来乘以......一个基于数组长度的随机字符串?技术上长度不是只有3个字符串吗?
我觉得它应该像
index = answers.random一样简单。这是否存在于JS或其他语言中?

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>


推荐答案

Python很容易。

It's easy in Python.

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

您正在查看的代码如此常见的原因通常是,当您在统计中讨论随机变量时,它的范围为[0,1)。如果您愿意,可以将其视为百分比。要使此百分比适合选择随机元素,请将其乘以范围,允许新值介于[0,RANGE]之间。 Math.floor()确保该数字是一个整数,因为当用作数组中的索引时,小数没有意义。

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.

您可以使用代码在Javascript中轻松编写类似的函数,我确信有很多JS实用程序库包含一个。类似

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.

这篇关于有没有一种简单的方法可以在JavaScript或任何其他编程语言中从数组中进行随机选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆