从 JavaScript 数组中随机选择一个项目

4
我正在制作一个可以回复我的信息的机器人。如果我发送“ Hi!”给机器人,它将回答“ 嗨,你好!”。我想知道,如何给机器人多个选择的答案?有没有一种方法可以使用JavaScript从响应数组中随机选择一个项?

1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - trincot
你看过 Math.Random 吗? - Abhinav Galodha
1
可能是从JavaScript数组中获取随机值的重复内容。 - Anderson Green
5个回答

19

使用 Math.random 乘以数组的长度,向下取整,作为索引进入数组。

像这样:

var answers = [
  "Hey",
  "Howdy",
  "Hello There",
  "Wotcha",
  "Alright gov'nor"
]

var randomAnswer = answers[Math.floor(Math.random() * answers.length)];

console.log(randomAnswer);


1
你可以在lodash中使用_.sample方法:

var responses = ["Well, hello there!", "Hello", "Hola", "Yo!", "What’s up?", "Hey there."];
console.log(_.sample(responses));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


0

我可以想到两种方法:

方法1:

  • 使用Math.random()函数获取(0-1,1不包括)之间的随机数。
  • 将其乘以数组长度以获取(0-arrayLength)之间的数字。
  • 使用Math.floor()获取索引范围从(0到arrayLength-1)。

const answers = [ "嗨", "你好", "你好呀", "你好啊", "你好呀" ]; const randomlyPickedString=answers[Math.floor(Math.random() * answers.length)]; console.log(randomlyPickedString);

方法2:

  • random(a, b)方法用于生成(a到b,b不包括)之间的数字。
  • 取floor值以将数字范围限制在(1到arrayLength)之间。
  • 减去1以获取索引范围从(0到arrayLength-1)。

const answers = [ "嗨", "你好", "你好呀", "你好啊", "你好呀" ] ;
const randomlyPickedString=answers[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);

为了更容易理解代码,我创建了一个额外的变量(randomlyPickedString)。您也可以不使用它来使用代码。

-1

没有JavaScript“命令”可以让你这样做。但是你可以在0到数组长度之间随机选择一个整数,然后获取该索引处的响应数组:

var response = responses[ parseInt( Math.random() * responses.length ) ];

一种更简洁的方法是:

var response = responses[ Math.random() * responses.length |0 ];

其中| 0表示与0进行按位或运算,在此情况下,它将浮点数(Math.random()返回从0到1的值)转换为最低的整数。


为什么不使用Math.floor而不是parseInt? - PaulBGD
那样也可以,但我选择使用这些示例是因为它们可能是他刚开始接触时在网上看到的。如果有人足够高级,了解Math.floor,他们可能也知道像|0这样的技巧。 - towc
1
我不同意,四舍五入在小学就教了,但是位运算是在大学里才学的。 - PaulBGD
实际上,他们在大学里没有教我位运算... - avalanche1

-1
你首先需要一个可能响应的数组。类似这样:
var responses = ["Well hello there!","Hello","Hola!"];

然后您可以使用Math.random函数。该函数返回小于1的十进制数,因此您需要将其转换为整数。

var responses = ["Well hello there!","Hello","Hola!"];
var responseIndex = Math.floor((Math.random() * 10) + 1);

另外,使用模数(%)运算符将您的随机数限制在数组索引范围内:

var responses = ["Well hello there!","Hello","Hola!"];
var totalResponses = responses.length;
var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;

最后,在数组中查找您的随机响应:
var responses = ["Well hello there!","Hello","Hola!"];
var totalResponses = responses.length;
var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
var response = responses[responseIndex];
alert(response);

1
Math.floor(Math.random() * array.length)足以生成一个随机索引。 - PaulBGD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接