有没有一种简单的方法可以从 JavaScript 或任何其他编程语言中的数组中进行随机选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9071573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a simple way to make a random selection from an array in JavaScript or any other programming language?
提问by nicedwar
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.
我正在阅读一本初学者的 JavaScript 书籍,其中包含一些代码,这些代码将编码器的输入(var 答案)与从数组(答案)中随机选择的字符串进行比较。这是一个猜谜游戏。
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?
我对随机选择字符串的方式感到困惑。该代码似乎是将 Math.random 函数乘以 answers 数组及其长度属性。检查一下,这似乎是从数组中随机选择的标准方法?为什么要使用数学运算符 * 来乘...输出...基于数组长度的随机字符串?从技术上讲,长度不是只有 3 个字符串吗?我只是觉得它应该像 index = answers.random 这样简单。这是否存在于 JS 或其他语言中?
<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>
回答by Matt Luongo
It's easy in Python.
在 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.
您正在查看的代码如此常见的原因是,通常,当您谈论统计中的随机变量时,它的范围是 [0,1)。如果你愿意,可以把它想象成一个百分比。为了使这个百分比适合选择一个随机元素,你将它乘以范围,允许新值介于 [0,RANGE) 之间。的Math.floor()
,就可以确保数是一个整数,因为如在数组索引使用时小数没有意义。
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
您可以使用您的代码轻松地在 Javascript 中编写一个类似的函数,我相信有很多 JS 实用程序库都包含一个。就像是
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.
然后您可以简单地编写choose(answers)
以获得随机颜色。
回答by Adam Rackis
Math.random
gives you a random number between 0 and 1.
Math.random
给你一个 0 到 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 thatwill truncate the decimal, and give you a random number within the bounds of your array
调用Math.floor
的是将截断小数,并给你数组的边界内的随机数
var arr = [1, 2, 3, 4, 5];
//array length = 5;
var rand = Math.random();
//rand = 0.78;
rand *= arr.length; //(5)
//rand = 3.9
rand = Math.floor(rand);
//rand = 3
var arr = [1, 2, 3, 4, 5];
//array length = 5;
var rand = Math.random();
//rand = 0.9999;
rand *= arr.length; //(5)
//rand = 4.9995
rand = Math.floor(rand);
//rand = 4 - safely within the bounds of your array
回答by scottmrogowski
Here you go
干得好
function randomChoice(arr) {
return arr[Math.floor(arr.length * Math.random())];
}
回答by Mikael Lepist?
Popular Underscore javascript library provides function for this, which can be used similar to python's random.choice :
流行的 Underscore javascript 库为此提供了函数,可以使用类似于 python 的 random.choice :
http://underscorejs.org/#sample
http://underscorejs.org/#sample
var random_sample = _.sample([1, 2, 3, 4, 5, 6]);
回答by Freestyle076
var choiceIndex = Math.floor(Math.random() * yourArray.length)
回答by CanSpice
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 value N
, you'll end up with a random number between 0 and N
.
Math.random
和类似的函数通常返回一个介于 0 和 1 之间的数字。因此,如果将随机数乘以可能的最高值N
,则最终会得到介于 0 和 之间的随机数N
。
回答by CoffeeRain
In Python it is...
在 Python 中它是...
import random
a=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'etc.']
print random.choice(a)
回答by Shakil
JavaScript
JavaScript
No. Vanilla JS does not provide any method like the following. You have to calculate, unfortunately.
不。Vanilla JS 不提供任何类似以下的方法。不幸的是,你必须计算。
function sample(array) {
return array[Math.floor(Math.random() * array.length)];
}
console.log(sample([1, 2, 3]));
console.log(sample([11, 22.3, "33", {"a": 44}]));
Try it out here.
But, if you are using lodash, the above method is already covered.
但是,如果您使用的是lodash,则上述方法已经涵盖。
let _ = require('lodash');
console.log(_.sample([11, 22.3, "33", {"a": 44}]));
Try it out here.
Python
Python
import random
random.choice([1, 2.3, '3'])
Try it out here.
Ruby
红宝石
using a single data type,
使用单一数据类型,
[1, 2, 3].sample
using multiple data types,
使用多种数据类型,
[1, 2.34, 'a', "b c", [5, 6]].sample
Try it out here.
Updated: JavaScript example added.
更新:添加了 JavaScript 示例。