【问题标题】:Popping list randomly with math.random() and math.floor()使用 math.random() 和 math.floor() 随机弹出列表
【发布时间】:2022-11-23 00:25:03
【问题描述】:

我想随机弹出 baby 变量列表,但它只是弹出 baby[1]。

<body>

    <h1 id="1">bebe</h1>
    <h1 id="2">tae</h1>

    <script>
        var baby = [document.getElementById('1').innerText, 
        document.getElementById('2').innerText]

        bot = Math.floor(Math.random() * baby.length)

        if (bot == 0) {
            baby.pop(0)
        }

        if (bot == 1) {
            baby.pop(1)
        }

        console.log(baby)
    </script>

</body>

【问题讨论】:

标签: javascript html


【解决方案1】:

那不是[].pop(),那是[].splice(start, deleteCount, replacement?)

var a = [1, 2, 3, 4, 5]
console.log(
  a.splice(3, 1), // [4]
  a,              // [1, 2, 3, 5]
)

【讨论】:

    【解决方案2】:

    Pop 总是删除列表中的最后一个元素。

    你想使用baby.splice(0, 1)baby.splice(1, 1)。第一个数字是索引,第二个数字是要删除的元素数。

    【讨论】:

      【解决方案3】:

      使用可以使用bot变量作为splice()索引:

      var baby = [document.getElementById('1').innerText, 
      document.getElementById('2').innerText]
      
      bot = Math.floor(Math.random() * baby.length)
      
      baby.splice(bot, 1) 
      
      console.log(bot)
      <h1 id="1">bebe</h1>
      <h1 id="2">tae</h1>

      【讨论】:

        猜你喜欢
        • 2014-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        • 1970-01-01
        • 2014-04-30
        • 2013-03-13
        相关资源
        最近更新 更多