【问题标题】:Pop up with a random string of an array弹出一个随机的数组字符串
【发布时间】:2015-09-11 11:09:58
【问题描述】:

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

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]);

如果你运行它,弹出的唯一内容就是“未定义”。为什么它不起作用?

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

【问题讨论】:

  • 实际上,当 (Math.random() * tasks.length) 给出 1 时,你减去 1,然后它应该是 0,0 的下限是 -1。因此,当您访问数组的 -1 属性时,您会变得未定义。

标签: javascript arrays random alert


【解决方案1】:

Math.random 返回一个介于 0(包括)和 1(不包括)之间的随机数,你将它乘以 3 并减去 1,所以你可以得到一个介于 -1 和 2 之间的数字(其中 2 是唯一的 - 值将始终低于 2)。当你floor 一个负值时,你得到-1。这就是为什么你有时会变得不确定

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

【讨论】:

  • 那我就不能删除-1吗?
【解决方案2】:

原因是,Math.random() 返回一个介于 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]);

【讨论】:

    【解决方案3】:

    这样就可以了:

    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]);
    

    【讨论】:

    • ((tasks.length -1) - 0 + 1)tasks.length 有何不同?
    • 你为什么要+ 0- 0
    猜你喜欢
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 2017-06-30
    相关资源
    最近更新 更多