【发布时间】: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