为什么这个JavaScript代码在控制台上打印"未定义"?

Ant*_*eev 6 javascript undefined read-eval-print-loop

我有以下JavaScript代码:

var counter = 0;
function printCounter(){
   console.log("counter=" + ++counter);
   setTimeout(printCounter, 1000);
}
printCounter();
Run Code Online (Sandbox Code Playgroud)

我希望它应该打印此输出:

counter=1
counter=2
counter=3
...
Run Code Online (Sandbox Code Playgroud)

但它打印如下:

counter=1
undefined  // <-- Notice this "undefined"
counter=2
counter=3
...
Run Code Online (Sandbox Code Playgroud)

为什么在第一次迭代后打印"undefined"?重要提示:只有在JavaScript控制台中执行代码时才会看到此类行为.如果它是页面的一部分,它可以正常工作.

Poi*_*nty 8

这是因为"printCounter()"函数本身会返回undefined.那是控制台告诉你表达式的结果.

通过添加return "Hello Anton!";到结尾更改"printCounter()" :-)

编辑 - 说它"返回undefined" 有点令人困惑; 实际上,它没有明确的回报,但它的效果是一样的.

  • ...所以`undefined`是*REPL评估的结果*但是由于*asynchronous*timer正在运行,它将继续调用`console.log` ... (2认同)