How to clone array

Asked

Viewed 164 times

0

I’m wandering about on a way to make sure that as all elements of the array in question, go all over again.

See this my source code below:

Code

<html>

<body>

    <button onclick="next()">APAGAR</button>

</body>

<script>
var total = 4,
    letras = ["A", "B", "C", "D"];

function next() {
    // Antes de começar a apagar o primeiro indice, conferir se array
    // está totalmente vazio e popular array novamente caso positivo
    if (total.length === 0) {
        // Para popular a array use
        total = letras.slice(0);
    }
    // A cada clique, eliminar o elemento [0]
    var indice = letras.splice(0, 1);
    alert(indice, letras);
}
</script>

</html>

But when it comes to the end, it does not return what I need. It would be to go back all over again as from the beginning. Like a roulette wheel.

  • I don’t quite understand, you want to remove the first element of the array every time you click the button and return the array without that element?

  • @Gabrielc. He is already removing. Now I need him to detect that the array being empty to re-populate it with elements of itself. That’s why I put in the title "clone".

  • then why are you initiating the variable total with the value 4, and then he’s checking out the property length? That way the parole won’t be true since total.length will return undefined

  • @Gabrielc. On another occasion had not defined this variable total this way. In another test had so assigned var total, link = [ .. ], but in the console it said that the variable was not defined total. So I decided to make this change, to see if I could.

  • @Gabrielc. I know I’m on the right track, because the method slice returns a copy of a array in a new object array. I just can’t seem to finish this step.

1 answer

2


You can reduce the value of total in 1 every time an element is removed, moreover, create a array called original so that it can be cloned by array letters. So when the total reaches 0, you repopulate the array and reset the value of total. See how the code looks:

 var total = 4, original = [ "A", "B", "C", "D" ], letras = [ "A", "B", "C",
        "D" ];

function next() {
    // Antes de começar a apagar o primeiro indice, conferir se array
    // está totalmente vazio e popular array novamente caso positivo
    if (total === 0) {
        // Para popular a array use
        alert("clonando");
        letras = original.slice(0);
        //reseta o valor de total
        total = 4;
    }
    // A cada clique, eliminar o elemento [0]
    var indice = letras.splice(0, 1);
    alert(indice);
    alert(letras);
        total -= 1;
    }
  • @Diegohenrique made a small edition, so I hope you have copied the part where the value of total

Browser other questions tagged

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