The variable has changed before you can explain this behavior of Chrome V8?

I wrote a javascript program and ran it in Chrome 7 when I came across some weird behavior. Now, in my code, with all the other things, it took me a while to realize that it wasn't me.

I have exhausted the code below.

<html> <script> 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 in Chrome 7, I get the output following it in the Javascript console:

 Printing before: [1000, 2000, 3000, 4000, 5000] ------------------------ Printing after: [1000, 2000, 3000, 4000, 5000] 

How does the first console.log call print a modified version of data_copy?

Now, if I uncomment the β€œwarning” and run the same code, I get what you usually 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?

Did this JIT optimization go awry?

Or am I missing something obvious?

+4
source share
2 answers

Change console.log(data_copy) to console.log(String(data_copy)) .

console.log efficiently dispatches an object via a link to the Chrome console. alert terminates your script, so the first registered data_copy receives the visualization until a later modification; without, the entire script exits before the console displays the data_copy link.

+4
source

See crbug.com/44720

+1
source

All Articles