Firefox 37上console.log()的奇怪行为 [英] Strange behaviour of console.log() on Firefox 37

查看:175
本文介绍了Firefox 37上console.log()的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几分钟前,在使用javascript的时候,我注意到了一个奇怪的行为: console.log()。事实上,它似乎记录扭曲的变量。看看下面的内容:

var res = document.getElementById(控制台。var arr = [1,2,3]; arr.push(4); res.innerHTML = JSON.stringify(arr)+'< br>' log(arr); arr.push(5); res.innerHTML + = JSON.stringify(arr); console.log(arr);

 < div id =res>< / div>  

它将正确的变量打印到 #res 中,但不能放入浏览器控制台(Firefox 37)





有人可以解释一下为什么会发生这种情况吗?

解决方案

您的日志记录,以便您获取数组的副本:



  var arr = [1,2,3]; arr.push(4); console.log(arr.slice()) ; arr.push(5); console.log(arr.slice());  

一切按预期运作。



我把实时跟踪作为一种可能性,因为下面的例子没有显示任何实时跟踪的证据:

 



这意味着日志排队,直到最后一次推入数组(直到你的javascript执行完成)之后,队列才会运行。 b
$ b

不错的发现...肯定是一些可能会吸引开发者的东西。

Some minutes ago, while playing with javascript, I noticed a strange behaviour of console.log(). In fact it seems to log "distorted" variables. Take a look to the following:

var res = document.getElementById("res");
var arr = ["1", "2", "3"];
arr.push("4");
res.innerHTML = JSON.stringify(arr)+'<br>';
console.log(arr);
arr.push("5");
res.innerHTML += JSON.stringify(arr);
console.log(arr);

<div id="res"></div>

It prints correct variables into #res but not into browser console (Firefox 37)

Could someone explain me why this happens?

解决方案

So, if you change your logging so that you're taking a copy of the array:

var arr = ["1", "2", "3"];
arr.push("4");
console.log(arr.slice());
arr.push("5");
console.log(arr.slice());

Everything works as expected.

I'm discounting "live" tracking as a possibility, because the following example does not display any evidence of live tracking:

var arr = ["1", "2", "3"];
console.log(arr);
var i;
i = setInterval(function(){
  arr.push(1);
  console.log(arr);
  if(arr.length>10)clearInterval(i)
},1000);

This implies that the logging is queued and the queue does not run until after the last push to the array (probably until your javascript has finished executing).

Nice find... definitely something that might catch out developers.

这篇关于Firefox 37上console.log()的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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