从javascript数组中选择一个随机项目 [英] pick a random item from a javascript array

查看:85
本文介绍了从javascript数组中选择一个随机项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个可以响应我的消息的机器人.

如果我向机器人发送 Hi!,它将通过 Well,hello!回答.我只是想知道,如何为机器人提供多种选择答案?是否可以使用JavaScript从响应数组中选择随机项目?

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?

推荐答案

使用Math.random *数组的长度(四舍五入)作为数组的索引.

Use Math.random * the length of the array, rounded down, as an index into the array.

赞:

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

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

console.log(randomAnswer);

这篇关于从javascript数组中选择一个随机项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆