在事实发生变化之前,你能否解释一下这款Chrome V8的行为? [英] Variable changed before the fact, can you explain this Chrome V8 behavior?
问题描述
当我遇到一些奇怪的行为时,我正在编写一个JavaScript程序并在Chrome 7中运行它。现在,在我的代码中,随着所有其他事情的发展,我花了一些时间才发现它不是我。
我已经提炼出了代码如下。
< html>
< script>
var data = [1,2,3,4,5];
var data_copy = []; (var i = 0; i< data.length; i ++){
data_copy.push(data [i])的
;
}
console.log(Before before:);
console.log(data_copy);
// alert(data_copy);
console.log(------------------------); (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>
当我在Chrome 7上运行这个时,我在Javascript控制台中得到以下输出:
打印前:
[1000,2000,3000,4000,5000]
------ ------------------
打印后:
[1000,2000,3000,4000,5000]
第一次调用console.log如何打印data_copy的更改版本?
现在,如果我取消注释警报并运行相同的代码,则可以得到您通常所期望的结果:
[1,2,3,4,5]
------------------------
打印后:
[1000,2000,3000,4000,5000]
我也尝试了代码node.js和我得到第二(正常)输出。
任何想法?
这是否会导致一些JIT优化错误?
或者我错过了一些明显的东西?
更改 console.log(data_copy)
至 console.log(String(data_copy))
。
console.log
通过引用Chrome控制台有效地发送对象。 alert
会中断您的脚本,以便第一个记录的 data_copy
在稍后的修改之前被渲染;如果没有,整个脚本将在控制台呈现 data_copy
引用前运行完成。
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>
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.
这篇关于在事实发生变化之前,你能否解释一下这款Chrome V8的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!