Empty vector displays the end result of the function

1

I'm doing tests with array / vector and as the first vector display should be shown empty, as second, would come full. What's the problem, why does it occur? And how can I fix it?

<ul><li>Murilo</li><li>Mariana</li><li>Steve</li><li>Mark</li><li>Couve</li></ul><scripttype="text/javascript">
    var lista = document.querySelectorAll("li");
    var vetor = new Array();
    console.log("Vetor sem arquivos");
    console.log(vetor);
    function insertIn(vetor, lista){
        for(var i = 0; i < lista.length; i++){
            vetor.push(lista[i]);
        }
    }insertIn(vetor, lista);
    function mostraDados(vetor){
        console.log("Vetor com arquivos");
        console.log(vetor);
    }mostraDados(vetor);
</script>
    
asked by anonymous 26.05.2017 / 15:26

1 answer

2

I believe this happens because the vector is a reference, and so the values are always inserted into that memory. See if this code helps you understand:

    var lista = document.querySelectorAll("li");
    var vetor = new Array();
    
    document.getElementById('encher_vetor').onclick = function () {    
    	insertIn(vetor, lista);
    }
    
    document.getElementById('mostrar_vetor').onclick = function () {    
    	mostraDados(vetor);
    } 
    
    document.getElementById('esvaziar_vetor').onclick = function () {    
    	vetor = [];
    }    
    
    function insertIn(vetor, lista){
        for(var i = 0; i < lista.length; i++){
            vetor.push(lista[i]);
        }
    }
    
    function mostraDados(vetor){
        console.log(vetor);
    }
<ul>
    <li>Murilo</li>
    <li>Mariana</li>
    <li>Steve</li>
    <li>Mark</li>
    <li>Couve</li>
</ul>
<br>
<input type="button" id="encher_vetor" value="Clique para preencher o vetor" />
<input type="button" id="mostrar_vetor" value="Clique para mostrar o vetor" />
<input type="button" id="esvaziar_vetor" value="Clique para esvaziar o vetor" />

The manipulated vector is always the same variable, same memory location.

    
26.05.2017 / 15:44