弹出一个数组的随机字符串

Pop up with a random string of an array

我正在尝试弹出一个警告框,其中包含一组句子中的一个随机句子。这是我的代码:

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var randomTask = Math.floor((Math.random() * tasks.length) - 1);

alert(tasks[randomTask]);

如果你 运行 它,流行音乐只会说 "undefined"。为什么不起作用?

感谢任何回答的人! :-)

原因是,Math.random() returns一个介于0和1之间的数字。

当数字为0.1xxx时,为

计算为

0.1xxxxx * 3 - 1

Math.floor(0.3xxxx - 1) = -1

array[-1]undefined

要解决此问题,您可以对生成的随机数使用 % 运算符。 % 将确保数字始终在 0arr.length - 1 之间。

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var randomTask = Math.floor((Math.random() * tasks.length) % tasks.length);

alert(tasks[randomTask]);

Math.random returns0(含)到1(不含)之间的随机数,乘以3减1,得到-1到2之间的数(其中 2 是独占的 - 值将始终低于 2)。当你 floor 一个负值时,你会得到 -1。这就是为什么你有时会得到 undefined

基本上,删除 - 1 它应该可以工作

这样做:

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var rand = Math.floor(Math.random() * ((tasks.length -1) - 0 + 1)) + 0;
alert(tasks[rand]);