chrome 调试控制台 笔记

console输出

蓝色小圈

chrome console输出中有时会出现蓝色背景圆圈,然后里面有个数字,代表同样内容输出了多少次:例如:

for(var i = 0;i < 3; i++){
    console.log(6)
}

 会出现上述情况。

Message stacking

If a message is consecutively repeated, rather than printing out each instance of the message on a new line, the Console "stacks" the messages and shows a number in the left margin instead. The number indicates how many times the message has repeated.

详细内容参考Google的文档Google Developers

ps. 这里要说明一下javascript的setTimeout函数,如果运行如下代码段:

1 for(var i = 0;i < 3; i++){
2     setTimeout('console.log(i)',1000);
3 }

会出现蓝色小圈,同样内容输出了10次,如下图:

这里需要说明的是‘98‘是setTimeout的返回值,控制台中可以使用clearTimeout来终止回调函数的执行。

连续10次输出同样的内容,说明这10次setTimeout共享了变量 i ,stackoverflow有讲解setTimeout in a for-loop and pass i as value:setTimeout函数将需要执行的代码放到事件循环队列中,等时间到的时候再调用回调函数。javascript中,变量的作用域是函数,上面的代码虽然每一次循环中分开执行,但所处域是一样的。所以,1000ms后,三个事件队列中的回调函数相继执行,使用此域中的变量 i ,故输出同样内容。javascript不能使用串行思想,要使用事件循环来考虑这个问题。

正确写法:

1 for(var i = 0;i < 3; i++){
2       (function(index){setTimeout(function(){console.log(index)},index*1000)})(i);
3 }

这里提到一下立即执行IIFE

如果上面写成:

1 for(var i = 0;i < 3; i++){
2       (function(index){setTimeout(console.log(index),index*1000)})(i);
3 }

或者

for(var i = 0;i < 3; i++){
      (function(index){setTimeout(function(){console.log(index)}(),index*1000)})(i);
}
//这里写法是错误的,如果在console敲function(){console.log('a')}()会出错,但在setTimeout中可以正常执行(似乎挑能够执行的正确代码执行,因为setTimeout函数的参数是代码段字符串)。匿名函数不能单独出现要立即执行,类似下面:
//(function(){console.log('a')})();

都不会按秒执行,会立即输出1,2,3。setTimeout函数第一个参数接收的是需要执行的代码段函数名(这里不能加括号,例如setTimeout(foo(), 1000)这种传参数是错误的,使用函数名加括号的话是立即执行的意思,延时执行没有起到效果。正确的使用方法是setTimeout(foo, 1000) )。可以做个实验:

1 function test(){console.log('hello')};
2 setTimeout(test, 1000);  //会在1秒后输出'hello'   
3 setTimeout(test(), 1000);  //会立即输出'hello'

undefined

输出中的undefined代表没有函数返回值,如果使用console.log("xxx")函数是会输出undefined,因为console.log函数没有返回值。对比这,在console中键入1+1则不会输出,因为表达式返回了值

posted on 2017-05-04 15:17  yuanww  阅读(509)  评论(0编辑  收藏  举报

导航