对于此特定变量,我有四种可能性之一->
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之间,med在45到60之间。 在我的innerHTML中,我要打印从数组中选择的变量返回的数字。当用户单击时,将启动包含此功能的功能。
document.getElementById("scenario").innerHTML = randomUrban;
但是,当它在HTML中打印时,它不会打印与该变量关联的数字,而是会打印它选择的数组号(例如0或1)。
如何获取要打印的变量(例如,如果选择lowVelocity,那么它打印的数字将是找到的随机数lowVelocity,例如39)而不是数组号?
答案 0 :(得分:3)
您可以只使用一个数组为您完成所有这些操作!
如果将速度添加到数组,则随机数可以用作该数组的索引。在下面的代码中,我们使用该数组的长度来设置随机数的限制,然后您可以简单地从velocities
数组中的随机数指示的位置访问值:
velocities[randomUrban][1]
这将使子数组位于randomUrban
所指示的位置,[1]将获得行中的第二个元素,即计算出的速度。
/* Add the velocities to an array or easier management */
var velocities= [
["lowVelocity", Math.random() * (45 - 30) + 30],
["medVelocity", Math.random() * (60 - 45) + 45],
["highVelocity",Math.random() * (80 - 60) + 45],
["hwyVelcoity" ,Math.random() * (100 - 80) +80]
]
/* Pick a random position from the velocities */
const randomUrban = Math.floor(Math.random() * velocities.length);
/* Print the velocity at that position. (Also includes the velocity name for illustration) */
document.getElementById("scenario").innerHTML =
velocities[randomUrban][0] + " = " + velocities[randomUrban][1];
<div id="scenario"></div>
注意:在您的示例中,您仅使用了4种速度中的2种,因此您只需将要从中选择的速度添加到randomVelocities
数组中即可。
答案 1 :(得分:1)
就您而言,只需使用
document.getElementById("scenario").innerHTML = window[velocities[randomUrban]];
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;
const velocities = ["lowVelocity", "medVelocity"];
const randomUrban = Math.floor(Math.random() * velocities.length);
console.log(randomUrban);// random from velocities
console.log(velocities[randomUrban]); //get variable name
console.log(window[velocities[randomUrban]]); // search in scope where the variables are declared in this case window
答案 2 :(得分:1)
document.getElementById("scenario").innerHTML = velocities[randomUrban];
怎么样?
答案 3 :(得分:1)
好吧,您正在尝试打印错误的变量; randomUrban
是包含选定的velocities
数组索引的变量。
一个快速(但非常脏)的修复程序将打印eval(velocities[randomUrban])
,但是eval()
由于安全问题已被弃用。
更长但更好的解决方案是将速度分组为单个类型为object的变量,并访问其键以检索数值:
const velObj = {
lowVelocity: Math.random() * (45 - 30) + 30,
medVelocity: Math.random() * (60 - 45) + 45,
highVelocity: Math.random() * (80 - 60) + 45,
hwyVelocity: Math.random() * (100 - 80) + 80
};
const velocities = ["lowVelocity", "medVelocity"];
const randomUrban = Math.floor(Math.random() * velocities.length);
const velKey = velocities[randomUrban];
document.getElementById("scenario").innerHTML = velObj[velKey];
<div id="scenario"></div>