1
I am doing tests with array/vector and, as first display of the vector should be shown empty, as second, would come full. What is the problem, why it occurs ? and how can I correct ?
<ul>
<li>Murilo</li>
<li>Mariana</li>
<li>Steve</li>
<li>Mark</li>
<li>Couve</li>
</ul>
<script type="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>
I tested in the Jsbin and apparently gave the expected result. For you came out 5 elements in the two outputs?
– Woss
@Andersoncarloswoss, yes, the 5 elements left when clicking on the array for details
– Murilo Melo
It is because you are printing the vector reference. If you show in the output only the content will appear correctly. console.log(JSON.stringify(vector));
– Don't Panic
I tested it here, and interestingly, when I debug it, it works fine, but when I let it run, it prints in both outputs all values
– Artur Trapp
@Everson, I don’t use JSON, but what would this vector reference and how it works ? would you give me a brief explanation ?
– Murilo Melo
Exacto @Arturotemplário
– Murilo Melo
Exact. Note that it shows the empty vector containing elements, that is, the first time the vector really does not have elements. However, the browser stores the vector’s memory address and, later, when the values are entered, it is inserted in this memory position. As the browser displays that reference, the values end up appearing as well. (Yes, that’s the answer, but I commented because I need to improve the text and make it clearer)
– Woss
Reference is a pointer to the memory where the contents of your variable are. When you use reference, any changes to it make, wherever it is referenced, the content is changed. From what I’ve seen here, Chrome understands that as you tampered with the reference when entering the content into the array, the content shown gets the reference value.
– Don't Panic
Thanks guys, now I understand better how it works :D
– Murilo Melo