问题描述
我有以下JavaScript代码:
I have following JavaScript code:
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
...
但它打印如下:
counter=1
undefined // <-- Notice this "undefined"
counter=2
counter=3
...
为什么在第一次迭代后打印undefined?重要提示:当在JavaScript控制台中执行代码时,我看到仅这样的行为。如果它是页面的一部分,它可以正常工作。
Why it prints "undefined" after first iteration? Important: I see such behavior only when the code executed in JavaScript console. If it's the part of a page, it works fine.
推荐答案
这是因为printCounter()函数本身返回未定义
。这是控制台告诉你表达式的结果。
It's because the "printCounter()" function itself returns undefined
. That's the console telling you the result of the expression.
通过添加更改printCounter()返回Hello Anton!;
到最后: - )
Change "printCounter()" by adding return "Hello Anton!";
to the end :-)
编辑—说它返回 undefined
有点令人困惑;实际上,它没有明确的回报,但它的效果相同。
edit — it's a little confusing to say it "returns undefined
"; really, it has no explicit return, but it's the same effect.
这篇关于为什么这个JavaScript代码打印“未定义”?在控制台上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!