I’ve got the following problem and I can’t seem to get why it’s not working the way I think it should be working:
function iterate(somelist){
anotherlist = [];
for(i = 0; i < somelist.length; i++){
anotherlist.push(somelist[i]);
console.log(anotherlist);
}
}
What I would expect this to do is log an increasingly growing list, but instead it just prints the complete list several times, as if it first pushes all variable into anotherlist and afterwards starts the log function. It doesn’t seem to matter wether I use a for or a foreach loop.
I really don’t get why it works like this and can’t seem to figure out a way to work around it.
Thanks in advance,
Bart
By the way, somelist in this case is an object on which I iterate, and it seems to make a difference, as I tried it with a normal array and that seems to work.
I suspect the console waits for the thread to finish before updating, perhaps so as not to interfere with performance too much. When the console UI is finally updated, the thread (and loop) has already finished and all logs reference the same array.
To work around it, you can call the array’s
slice()method to make a copy of the array whilst logging: