在console.log中错误的值 [英] Wrong value in console.log

查看:108
本文介绍了在console.log中错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:


我在JavaScript中有以下代码片断,它们的输出让我觉得出了问题。



1。

  a = 2; $ c> 


console.log(a);
a + = 2;
console.log(a);

输出: 2 4 ;如预期的那样

2。

  T = [0,2]; 
console.log(t);
t [0] + = 2;
console.log(t);

输出:[2,2] [2,2]



不应该输出 [0,2] [2,2] 上述两种情况的区别是什么?在这两种情况下的不同答案是什么?

解决方案

这是因为日志会延迟到Chrome有时间做到这一点(即你的脚本释放CPU)。



试试这个来理解会发生什么:

  var t = [0,2]; 
console.log(t);
setTimeout(function(){
t [0] + = 2;
console.log(t);
},1000);

它输出您的期望。

这是Chrome的错误吗?也许是优化的副作用。至少这是一个危险的设计...



为什么会有差异?我猜想Chrome会在第一种情况下暂时存储它必须记录的内容,作为第一种情况下的主要(不可变)值,作为最后一种情况下的数组指针。


Possible Duplicate:
Is Chrome's JavaScript console lazy about evaluating arrays?

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);

Output:2 4 ; as expected

2.

t=[0,2];
console.log(t);
t[0]+=2;
console.log(t);

Output: [2,2] [2,2]

Shouldn't the output be [0,2] [2,2] ? And whats the difference between the above two cases that results in the different answers in both the cases?

解决方案

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);

It outputs what you expect.

Is that a bug of Chrome ? Maybe a side effect of an optimization. At least it's a dangerous design...

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中错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆