我有以下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控制台中执行代码时才会看到此类行为.如果它是页面的一部分,它可以正常工作.