问题描述
我正在看一个朋友做的一些代码,偶然发现这条线,我认为这是一个错误(例如,经过简化).
I was having a look at some code a friend did and stumbled across this line which I thought was an error (simplified for example)..
for (g = 0; 10 > g; g++); {
alert(g);
}
但是它仍然执行,并警告"10".为什么是这样?这是javascript中的专用函数吗?
However it still executes, and alerts "10". Why is this? Is this a purpose built function in javascript?
推荐答案
您的 g
变量位于全局上下文中,因此可以在 for
循环之外进行访问.循环完成了它的工作,并增加了 g
十次.
两个 {}
表示JavaScript中的一个块,不会引起任何错误.
Your g
variable is within the global context, so it is accessible outside of a for
loop.The loop did its job, and incremented g
10 times.
Two {}
indicate a block in JavaScript and won't cause any error.
编辑:由于未定义 g
变量,因此没有 for
循环不会警告任何内容.
Edit: it is not alerting anything without a for
loop, because the g
variable is not defined.
这篇关于为什么仍然使用分号的for循环仍然执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!