变量未写入数组 - Javascript

时间:2016-08-25 13:42:36

标签: javascript html arrays function

我正在创建一个简单的“宾果调用者”工具。数组中会有一组短语 - 我想选择随机短语。然而,一旦挑选一个,我不希望它再次被选中。

目前 - 我只是使用随机数(用于从数组中提取短语)。

我有一个生成随机数的函数 - 根据函数中的短语数量,然后检查它是否存在于绘制数字的数组中。如果它没有 - 它被添加,如果它然后该功能停止(我希望该功能再次运行 - 我从内部调用该函数,但它表现不正常,所以我简化它停止!)。

拾取的数字也显示为绘制的数字数组。

但是,该函数没有显示我的预期:一旦到达重复的数字,代码就会开始向数组中添加几个元素......我希望它不会添加如果它已经存在的话......

<!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使它看起来像它!)

4 个答案:

答案 0 :(得分:2)

因为你的drawn.push(x);被置于for循环中。

每次drawn[i] === x失败时,都会将x推送到drawn的末尾。然后,您的drawn将以多个x结束。将您的drawn.push(x);移出for循环以防止它。

更好的是,使用indexOf()检查x中是否已drawn

if (drawn.indexOf(x) === -1) {
    drawn.push(x);
}

答案 1 :(得分:2)

像这样。

<!DOCTYPE HTML>
<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)));
      console.log(x);

      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 if (drawn.indexOf(x) == -1) {
        drawn.push(x);
        document.getElementById("never").innerHTML = x;
        document.getElementById("collection").innerHTML = drawn;
        document.getElementById("first").innerHTML = "Not First Number";
      }
    }
  </script>
</body>

</html>

答案 2 :(得分:1)

问题是它应首先检查所有元素并检查x是否存在,然后推送/忽略该元素,即替换

        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";
            }
        }

类似

        var is_present = false;
        for (var i=0;i<count;i++)
        {
           if (drawn[i] === x)
               {
                   is_present=true;break;
               }
        }

            if(!is_present)
            {
            drawn.push(x); 
            document.getElementById("never").innerHTML = x;
            document.getElementById("collection").innerHTML = drawn;
            document.getElementById("first").innerHTML = "Not First Number";
            }

答案 3 :(得分:1)

您可以尝试的是在绘制短语时,将其从原始数组中删除,然后将其添加到绘制的数组中。这样,您甚至不必检查绘制的数组中是否存在该短语,因为原始数组将始终包含未绘制的短语

var original = ['one', 'two', 'three', 'four', 'five', 'six'];
var drawn = []

function getIndex() {
  var randX = Math.floor(Math.random() * original.length;
  return randX;
}

var index = getIndex();
var drawnWord = original[ index ];
// Remove the word from original array
original.splice(index, 1);
// Add word to drawn array
drawn.push( drawnWord );

// Then proceed to display your words
// ...