问题描述
可能的重复:
Chrome 的 JavaScript 控制台是否懒得计算数组?
我在 javascript 中有以下片段,它们的输出让我觉得出了点问题.
I have the following snippets in javascript whose output makes me feel that something is going wrong.
1.
a=2;
console.log(a);
a+=2;
console.log(a);
输出:2 4
;正如预期的
Output:2 4
; as expected
2.
t=[0,2];
console.log(t);
t[0]+=2;
console.log(t);
输出:[2,2] [2,2]
输出不应该是 [0,2] [2,2]
? 以上两种情况有什么区别,导致两种情况的答案不同?
推荐答案
这是因为日志延迟到 Chrome 有时间去做(即您的脚本释放 CPU).
It's because the log is delayed until Chrome has time to do it (i.e. your scripts releases the CPU).
试试这个来了解会发生什么:
Try this to understand what happens :
var t=[0,2];
console.log(t);
setTimeout(function() {
t[0]+=2;
console.log(t);
}, 1000);
它输出您期望的内容.
这是Chrome的错误吗?也许是优化的副作用.至少这是一个危险的设计......
Is that a bug of Chrome ? Maybe a side effect of an optimization. At least it's a dangerous design...
为什么会有区别?我想 Chrome 会临时存储它必须记录的内容,在第一种情况下作为主要(不可变)值,在最后一种情况下作为指向数组的指针.
Why is there a difference ? I suppose Chrome stores temporarily what it must log, as a primary (immutable) value in the first case, as a pointer to the array in the last case.
这篇关于console.log 中的值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!