【问题标题】:Variable not being written to array - Javascript变量未写入数组 - Javascript
【发布时间】: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


【解决方案1】:

因为你的 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);
}

【讨论】:

  • if (drawn.indexOf(x) !== -1) { 应该是 if (drawn.indexOf(x) == -1) {。仅当不存在时才将值推送到数组中
  • 太棒了 - 我不知道 indexOf 函数非常感谢。
【解决方案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>

【讨论】:

    【解决方案3】:

    问题是它应该首先遍历所有元素并检查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";
                }
    

    【讨论】:

      【解决方案4】:

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

      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
      // ...
      

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多