我试图在1-75之间生成一个随机数,然后将其与数组进行比较,以便稍后我可以将结果用作if / else语句的参数; (即,如果数字在数组中,请执行此操作,否则执行此操作。)
以下是相关代码:
var pickable = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75];
var grid = [7,14,8,10,4,25,18,20,26,27,37,33,40,45,32,48,55,49,52,53,61,63,74,73,67];
function pick()
{
var temp1 = Math.floor(Math.random() * (pickable.length));
var temp2 = temp1.toString();
var check = grid.indexOf(temp2);
alert (check + "\n" + grid);
}
但是这段代码并没有给我一些有意义的索引号;当数字明显在数组中时返回-1,返回不在数组中的数字的其他数字,或返回与数组中数字位置没有明显关系的数字。为什么这不起作用,什么会更好?请记住,我只是在学习编码,所以请详细解释。
经过一些实验,我发现它正在做的是选择随机数,将其写入屏幕上的适当位置,然后在使用该数字之前减去循环的迭代次数检查索引。 (我想。)换句话说,我第一次按下按钮,它在屏幕上显示48,但搜索索引47.下次我点击按钮它显示56,但搜索54,等等。是整个功能:
function pick()
{
if (pickable.length > 0)
{
var temp1 = Math.floor(Math.random() * (pickable.length));
var temp2 = temp1.toString();
var check = grid.indexOf(temp2);
alert ("index: " + check + "\nball: " + temp1 + "\n");
document.getElementById("ballNum").innerHTML = pickable[temp1];
pickable[temp1] = pickable[0];
pickable.shift();
picked.push(document.getElementById("ballNum").innerHTML);
document.getElementById("pickedNums").innerHTML = picked.join("| ");
}
else
{
alert("You are out of Bingo balls! \nPlease start over by clicking the " +
" \n\"Populate Board\" button.");
}
}