Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use shift inside a loop?

Tags:

javascript

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?

like image 770
Cato Johnston Avatar asked Jan 17 '23 23:01

Cato Johnston


2 Answers

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());
like image 184
Guffa Avatar answered Jan 24 '23 10:01

Guffa


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.

like image 27
Jon Newmuis Avatar answered Jan 24 '23 11:01

Jon Newmuis