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.log
doesn'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 b
variable, not the state when each console.log
call was made.
To get the desired ouput you would have to make a flash copy of the state of the variable for each console.log
call:
console.log(b.toString());
This is a side-effect of the console.log
statements not being printed as the statements are executed. Note that if you replace your console.log
with alert
, the code works as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With