为什么仍然使用分号的for循环仍然执行? [英] Why does a for loop with a semicolon after it still execute?

查看:59
本文介绍了为什么仍然使用分号的for循环仍然执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个朋友做的一些代码,偶然发现这条线,我认为这是一个错误(例如,经过简化).

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?

JS小提琴

推荐答案

您的 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循环仍然执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆