Variable changed before the fact, can you explain this Chrome V8 behavior?
I was writing a javascript program and running it in Chrome 7, when I encountered some strange behavior. Now, in my code, with all the other stuff going on, it took me some time to figure out it wasn't me.
I have distilled the essence of the code below.
<html>
<script>开发者_如何学JAVA;
var data = [1,2,3,4,5];
var data_copy = [];
for (var i=0; i<data.length; i++){
data_copy.push(data[i]);
}
console.log("Printing before:");
console.log(data_copy);
//alert(data_copy);
console.log("------------------------");
for (var i=0; i<data_copy.length; i++){
data_copy[i] = data_copy[i] * 1000;
}
console.log("Printing after:");
console.log(data_copy);
</script>
</html>
When I run this on Chrome 7, I get the output that follows in the Javascript console:
Printing before:
[1000, 2000, 3000, 4000, 5000]
------------------------
Printing after:
[1000, 2000, 3000, 4000, 5000]
How come the first call to console.log prints the changed version of data_copy?
Now, if I uncomment the "alert" and run the same code, I get what you would normally expect:
Printing before:
[1, 2, 3, 4, 5]
------------------------
Printing after:
[1000, 2000, 3000, 4000, 5000]
I also tried the code in node.js and I get the second (normal) output.
Any ideas?
Is this some JIT optimization gone awry?
Or am I missing something obvious?
Change console.log(data_copy)
to console.log(String(data_copy))
.
console.log
effectively sends the object by reference to Chrome's Console. alert
interrupts your script so the first logged data_copy
gets rendered before the later modification; without, the entire script runs to completion before the console renders either data_copy
reference.
See crbug.com/44720
精彩评论