-1

I want to randomize the popping of the list of the baby variable, but it's only popping the 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>
Ame Suzuki
  • 59
  • 4

3 Answers3

1

that's not [].pop(), that's [].splice(start, deleteCount, replacement?)

var a = [1, 2, 3, 4, 5]
console.log(
  a.splice(3, 1), // [4]
  a,              // [1, 2, 3, 5]
)
Dimava
  • 7,654
  • 1
  • 9
  • 24
1

Pop always removes the last element in the list.

You want to use baby.splice(0, 1) and baby.splice(1, 1). The first number is the index and the second number is the number of elements you want to remove.

David
  • 38
  • 5
1

pop() does not take any arguments, it always remove the last index.


You can use the bot variable as the splice() index:

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

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

baby.splice(bot, 1) 

console.log(baby)
<h1 id="1">bebe</h1>
<h1 id="2">tae</h1>

Note: Be careful when using Integers as ID:

0stone0
  • 34,288
  • 4
  • 39
  • 64