How to Clone Array

0

I'm wandering about a means of getting all elements of the array in question back, 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 come back all over again at first. Like a roulette.

    
asked by anonymous 18.03.2017 / 20:32

1 answer

2

You can reduce the value of total to 1 every time an element is removed, in addition, create a array called original so that it can be cloned by array when total reaches 0, you repopulate array and reset total . Here's 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;
    }
    
18.03.2017 / 20:52