有没有一种简单的方法可以从 JavaScript 或任何其他编程语言中的数组中进行随机选择
Is there a simple way to make a random selection from an array in JavaScript or any other programming language?
我正在阅读一本初学者的JavaScript书,其中包含一些代码,这些代码将编码器的输入(var答案(与数组中随机选择的字符串(答案(进行比较。这是一个猜谜游戏。
我对随机选择字符串的方式感到困惑。该代码似乎将 Math.random 函数乘以答案数组及其长度属性。环顾四周,这似乎是从数组中进行随机选择的标准方法?为什么要使用数学运算符 * 来乘...外。。。基于数组长度的随机字符串?从技术上讲,长度不是只有 3 根字符串吗?我只是觉得它应该是简单的东西,比如索引 = 答案.随机。这在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>
这在 Python 中很容易。
>>> import random
>>> random.choice(['red','green','blue'])
'green'
您正在查看的代码如此常见的原因是,通常,当您谈论统计中的随机变量时,它的范围为 [0,1]。如果您愿意,可以将其视为百分比。要使此百分比适合选择随机元素,请将其乘以范围,允许新值介于 [0,RANGE] 之间。Math.floor()
确保数字是整数,因为小数在用作数组中的索引时没有意义。
您可以使用您的代码轻松地在 Javascript 中编写类似的函数,我相信有很多 JS 实用程序库包含一个。类似的东西
function choose(choices) {
var index = Math.floor(Math.random() * choices.length);
return choices[index];
}
然后,您可以简单地编写choose(answers)
以获得随机颜色。
你去吧
function randomChoice(arr) {
return arr[Math.floor(arr.length * Math.random())];
}
Math.random
给你一个介于0和1之间的随机数。
将此值乘以数组的长度将得到一个严格小于数组长度的数字。
调用 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
流行的下划线 JavaScript 库为此提供了函数,可以使用类似于 python 的 random.choice :
http://underscorejs.org/#sample
var random_sample = _.sample([1, 2, 3, 4, 5, 6]);
JavaScript
不。香草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}]));
在这里尝试一下。
但是,如果您使用的是 lodash,则上述方法已经涵盖。
let _ = require('lodash');
console.log(_.sample([11, 22.3, "33", {"a": 44}]));
在这里尝试一下。
蟒
import random
random.choice([1, 2.3, '3'])
在这里尝试一下。
红宝石
使用单一数据类型,
[1, 2, 3].sample
使用多种数据类型,
[1, 2.34, 'a', "b c", [5, 6]].sample
在这里尝试一下。
更新:添加了 JavaScript 示例。
Math.random
和类似的函数通常返回一个介于 0 和 1 之间的数字。因此,如果将随机数乘以可能的最高值 N
,则最终会得到一个介于 0 和 N
之间的随机数。
var choiceIndex = Math.floor(Math.random() * yourArray.length)
GoLang:
只需获取一个随机数(在数组范围内(,然后从数组中选择一个项目,例如:
array := []string{ "item1" , "item2" , "item3" }
n := rand.Intn(len(reasons))
fmt.Print("The random item is: ", array[n])
在 Python 中它是...
import random
a=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'etc.']
print random.choice(a)
我测试了每个元素的不同可能性,这更好,因为每个元素都有相同的可能性:
classMates = ["bb", "gg", "jj", "pp", "hh"];
k = classMates.length - 0.5;
function ran(){
p = Math.round(Math.random() * k);
console.log(classMates[p])
}
ran()
当它只是数组时很简单,但是当我们有一个对象时,我们可以这样做:
function random_choice(array, isObject = false){
if(isObject){
const len = Object.keys(array);
const rand = Math.floor(Math.random() * len.length);
for (let l = 0; l < len.length; l++) {
if (l == rand) {
return array[len[l]];
}
}
} else {
const rand = Math.floor(Math.random() * array.length);
for (let l = 0; l < array.length; l++) {
if (l == rand) {
return array[l];
}
}
}
}
例:
function random_choice(array, isObject = false){
if(isObject){
const len = Object.keys(array);
const rand = Math.floor(Math.random() * len.length);
for (let l = 0; l < len.length; l++) {
if (l == rand) {
return array[len[l]];
}
}
} else {
const rand = Math.floor(Math.random() * array.length);
for (let l = 0; l < array.length; l++) {
if (l == rand) {
return array[l];
}
}
}
}
const obj = {
el1: 0,
el2: 1,
el3: 2,
el4: 3,
el5: 4,
el6: 5,
el7: 6,
el8: 7,
el9: 8,
el10: 9
};
const arr = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
];
console.log('With Object'n',random_choice(obj, true));
console.log('Only array'n', random_choice(arr));
- 我们可以使用任意的编程语言来动态化HTML页面吗
- JavaScript是同步编程语言,不是吗
- 有没有办法在编程语言中使用 LaTex 公式进行实际计算
- 从 Web 抓取数据并同时执行 api 调用的编程语言
- 为什么有些编程语言允许自动包含分号
- 是否可以使用 PHP 或 JavaScript 或任何其他编程语言在客户端计算机中存储大约 1 MB 的数据
- 一种编程语言可以同时是客户端和服务器端吗
- 如何从字符串中检测编程语言
- 有没有一种简单的方法可以从 JavaScript 或任何其他编程语言中的数组中进行随机选择
- javascript/html/其他编程语言的PDF文件
- 有没有一种工具可以从一种编程语言转换为另一种编程
- 浏览器游戏的编程语言是什么
- 如何在不同的编程语言中使用相同的正则表达式
- 如何制作完全属于自己的编程语言?我试过了.(并# 39;t工作)
- 这是最好的编程语言
- 更改客户端编程语言中的键盘语言
- 从代码片段中检测编程语言
- Javascript基本怀疑oop或obp,脚本或编程语言
- 如何使用.net框架或c#编程语言获取JavaScript变量的值
- 我如何在Javascript编程语言中从键盘输入