【发布时间】:2020-12-21 12:09:49
【问题描述】:
我有这个特定变量的四种可能性之一 -->
var lowVelocity = Math.random() * (45 - 30) + 30;
var medVelocity = Math.random() * (60 - 45) + 45;
var highVelocity = Math.random() * (80 - 60) + 45;
var hwyVelcoity = Math.random() * (100 - 80) +80;
在一种情况下,我可能有 lowVelocity 和 medVelocity,所以我只想在这两者之间随机选择。所以我这样做了:
const velocities = ["lowVelocity", "medVelocity"];
const randomUrban = Math.floor(Math.random() * velocities.length);
这很有效 - 它现在选择我感兴趣的两种速度之一。低速在 30 到 45 之间,中速在 45 到 60 之间。 在我的 innerHTML 中,我想打印从数组中选择的变量返回的数字。当用户单击 this 时,将启动一个包含 this 的函数。
document.getElementById("scenario").innerHTML = randomUrban;
但是当它在 HTML 中打印时,它不会打印与变量关联的数字,而是打印它选择的数组编号(如 0 或 1)。
如何获取要打印的变量(例如,如果它选择了 lowVelocity,那么它打印的数字将是找到的随机数 lowVelocity,例如 39)而不是数组编号?
【问题讨论】:
标签: javascript html arrays random