【发布时间】:2016-08-25 13:42:35
【问题描述】:
我正在创建一个简单的“bingo caller”工具。数组中会有一组短语 - 我想选择随机短语。但是,一旦被选中,我不想再被选中。
目前 - 我只是使用随机数(将用于从数组中提取短语)。
我有一个生成随机数的函数 - 基于函数中的短语数,然后检查它是否存在于绘制的数字数组中。如果没有 - 如果有,则添加,然后函数停止(我希望函数再次运行 - 我是从自身内部调用函数,但它的行为不正常,所以我已将其简化为停止!)。
选中的号码也显示为抽奖号码数组。
但是,该函数并没有显示我期望的结果:一旦到达重复的数字,代码就开始向数组中添加几个元素...我希望它不会添加如果它已经存在的话......
<!DOCTYPE HTML SYSTEM>
<html>
<head>
<title>Teaching Styles Bingo</title>
<script type="text/javascript">
var words = [
'One',
'Two',
'Three',
'Four',
'Five',
'Six'
];
var drawn=[];
</script>
</head>
<body>
<button onclick="getNum()">Click me</button>
<p id="never">Hello</p>
<p id="collection"></p>
<p id="first"></p>
<script type="text/javascript">
// random number -> make it x
// then, check is it the first number? If so - add to array
// if not, then check: is it already in the array? If so - stop the function
// if not, add it to the array and wait for further instruction
// output to document the number picked and the contents of the array so far.
function getNum()
{
var x=(Math.floor(Math.random() * (words.length)));
var count=drawn.length;
if (count<1)
{
drawn.push(x);
document.getElementById("never").innerHTML = x;
document.getElementById("collection").innerHTML = drawn;
document.getElementById("first").innerHTML = "First Number";
}
else
{
for (var i=0;i<count;i++)
{
if (drawn[i] === x)
{
return;
}
else
{
drawn.push(x);
document.getElementById("never").innerHTML = x;
document.getElementById("collection").innerHTML = drawn;
document.getElementById("first").innerHTML = "Not First Number";
}
}
}
}
</script>
</body>
</html>
如果数组中存在值,为什么脚本不简单地添加任何内容?为什么脚本一次将多个数字添加到数组中(或者至少 - html 的输出使它看起来像它!)
【问题讨论】:
-
如果值已经存在,你想添加空值还是什么都不添加(
'')?
标签: javascript html arrays function