我正在制作一个可以回复我的信息的机器人。如果我发送“ Hi!”给机器人,它将回答“ 嗨,你好!”。我想知道,如何给机器人多个选择的答案?有没有一种方法可以使用JavaScript从响应数组中随机选择一个项?
使用 Math.random 乘以数组的长度,向下取整,作为索引进入数组。
像这样:
var answers = [
"Hey",
"Howdy",
"Hello There",
"Wotcha",
"Alright gov'nor"
]
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
console.log(randomAnswer);
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>
我可以想到两种方法:
方法1:
const answers = [ "嗨", "你好", "你好呀", "你好啊", "你好呀" ]; const randomlyPickedString=answers[Math.floor(Math.random() * answers.length)]; console.log(randomlyPickedString);
方法2:
为了更容易理解代码,我创建了一个额外的变量(randomlyPickedString)。您也可以不使用它来使用代码。const answers = [ "嗨", "你好", "你好呀", "你好啊", "你好呀" ] ;
const randomlyPickedString=answers[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);
没有JavaScript“命令”可以让你这样做。但是你可以在0到数组长度之间随机选择一个整数,然后获取该索引处的响应数组:
var response = responses[ parseInt( Math.random() * responses.length ) ];
一种更简洁的方法是:
var response = responses[ Math.random() * responses.length |0 ];
其中| 0
表示与0进行按位或运算,在此情况下,它将浮点数(Math.random()
返回从0到1的值)转换为最低的整数。
|0
这样的技巧。 - towcvar 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);
Math.Random
吗? - Abhinav Galodha