问题
I am making a bot that can respond to my messages.
If i send Hi!
to the bot, it will answer With Well, hello there!
. I was just wondering, what do I do to give the bot multiple choices of answers? Is there a way to pick a random item from a responses array using JavaScript?
回答1:
Use Math.random * the length of the array, rounded down, as an index into the array.
Like this:
var answers = [
"Hey",
"Howdy",
"Hello There",
"Wotcha",
"Alright gov'nor"
]
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
console.log(randomAnswer);
回答2:
You can use the _.sample method in lodash:
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>
回答3:
There's no JavaScript "command" that allows you to do this. But what you can do, is pick an integer at random from 0 to the length of the array, and get the array of responses at that index:
var response = responses[ parseInt( Math.random() * responses.length ) ];
A more concise way to do this is:
var response = responses[ Math.random() * responses.length |0 ];
where | 0
indicates the bitwise-or with 0, which in this case just turns a floating point number (Math.random()
returns values from 0 to 1) into its lowest integer
回答4:
You would first need an array of possible responses. Something like this:
var responses = ["Well hello there!","Hello","Hola!"];
You can then use the Math.random
function. This function returns a decimal < 1, so you will need to convert it to an integer.
var responses = ["Well hello there!","Hello","Hola!"];
var responseIndex = Math.floor((Math.random() * 10) + 1);
Also, use the modulus (%
) operator to keep your random number within the confines of your array indexes:
var responses = ["Well hello there!","Hello","Hola!"];
var totalResponses = responses.length;
var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
Finally, lookup your random response in the array:
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);
来源:https://stackoverflow.com/questions/42211863/pick-a-random-item-from-a-javascript-array