When I run this code:
var a = ['a','b','c'];
var b = ['a','b','c'];
for(i = 0; i <= a.length-1; i++){
b.shift();
console.log(b);
}
I expected this output:
['b','c']
['c']
[]
But I get this output:
[]
[]
[]
Why?
And how do I get my expected output?
This is a known problem in Chrome. It’s because the
console.logdoesn’t make a copy of what you want to display, it just stores the reference.As the log isn’t updated immediately, but once your function ends and the browser updates the user interface, the log will show the current state of the
bvariable, not the state when eachconsole.logcall was made.To get the desired ouput you would have to make a flash copy of the state of the variable for each
console.logcall: