为什么这段 JavaScript 代码在控制台上打印“未定义”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10263190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:13:14  来源:igfitidea点击:

Why does this JavaScript code print "undefined" on the console?

javascriptundefinedread-eval-print-loop

提问by Anton Moiseev

I have following JavaScript code:

我有以下 JavaScript 代码:

var counter = 0;
function printCounter(){
 ? console.log("counter=" + ++counter);
 ? setTimeout(printCounter, 1000);
}
printCounter();

I expect that it should print this output:

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

counter=1
counter=2
counter=3
...

But instead it prints following:

但它会打印以下内容:

counter=1
undefined  // <-- Notice this "undefined"
counter=2
counter=3
...

Why it prints "undefined" after first iteration? Important: I see such behavior onlywhen the code executed in JavaScript console. If it's the part of a page, it works fine.

为什么在第一次迭代后打印“未定义”?重要提示:只有在 JavaScript 控制台中执行代码时,我才会看到这种行为。如果它是页面的一部分,它工作正常。

回答by Pointy

It's because the "printCounter()" function itself returns undefined. That's the console telling you the result of the expression.

这是因为“printCounter()”函数本身返回undefined. 那是控制台告诉您表达式的结果。

Change "printCounter()" by adding return "Hello Anton!";to the end :-)

通过添加return "Hello Anton!";到末尾来更改“printCounter()” :-)

edit— it's a little confusing to say it "returns undefined"; really, it has no explicit return, but it's the same effect.

编辑- 说它“返回undefined”有点令人困惑;真的,它没有明确的回报,但效果是一样的。