I always want to delete the first index every time I click a button. How do I do it?

Asked

Viewed 40 times

0

Seen what I tried:

<html>

<body>
<script>
    var nome = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

    var remover = nome.slice(0);

    function shuffle(array) {
        return (Math.round(Math.random()) - 1);
        remover.splice(array, 1);
    }

    shuffle(nome);

    alert(nome);
</script>

</body>

</html>

But did not know how to add a button for such a purpose and yet this code does not make the purpose.

  • 1

    forehead el.addEventListener('click', function(){ nome.shift(); }); If it doesn’t work or it’s not what you want you have to explain the question better....

  • The method shuffle() is returning a value before you run the splice() , maybe that’s the problem.

  • @Diegohenrique what I meant is that if your button runs the method shuffle(array), the problem lies in the fact that it performs return (Math.round(Math.random()) - 1); before executing remover.splice(array, 1);, thus the method returns before the splice() run, and this may be the problem in your code.

1 answer

3


Your code is a little fuzzy and it doesn’t match what you ask for in the title, here’s what you ask for in the question heading:

var first_ele;
var btn = document.getElementById('btn');
var nome = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
btn.addEventListener('click', function() {
  first_ele = nome.shift();
  console.log(first_ele, nome)
});
<button id="btn">apagar primeiro ele</button>

With splice() pharisees:

...
first_ele = nome.splice(0, 1);
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.