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?
-
I do get your desired output.. I guess the console.log isn't a console.log in your current code.Johan– Johan2011年12月26日 12:13:02 +00:00Commented Dec 26, 2011 at 12:13
-
I'm getting the exact output you expect with the same codeNabab– Nabab2011年12月26日 12:13:51 +00:00Commented Dec 26, 2011 at 12:13
-
Your code is working correctly for me. What you've specified as expected output is exactly what i get when i run your code from Firebug console. In Chrome console, i'm getting the same output as what you're getting. So looks like an issue in Chrome?techfoobar– techfoobar2011年12月26日 12:14:14 +00:00Commented Dec 26, 2011 at 12:14
-
Hmm.. Interesting.. Looks like Chrome's console.log caches the output and flushes it out together after the loop! If you do a shift() and log (not in the loop), you'll get the correct output. But if you put it in a loop, it prints out the final value of b in all three cases!techfoobar– techfoobar2011年12月26日 12:16:56 +00:00Commented Dec 26, 2011 at 12:16
-
It's a webkit "issue" with console.log, there are other references to it here on so. Another "fix" is to use tostring() in your logJ. Holmes– J. Holmes2011年12月26日 12:18:16 +00:00Commented Dec 26, 2011 at 12:18
3 Answers 3
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());
4 Comments
array.slice()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.
Comments
Or change the log paramater to be an expression as per my answer to Javascript Funky array mishap
console.log ('' + b);