我有以下JavaScript代码:
var counter = 0;
function printCounter(){
console.log("counter=" + ++counter);
setTimeout(printCounter, 1000);
}
printCounter();
我希望它应该输出以下输出:
counter=1
counter=2
counter=3
...
但是,它打印以下内容:
counter=1
undefined // <-- Notice this "undefined"
counter=2
counter=3
...
为什么在第一次迭代后打印“未定义”?重要说明:仅当在JavaScript控制台中执行代码时,我才会看到这种行为。如果它是页面的一部分,则可以正常工作。
茅侃侃
相关分类