美文网首页
015|JavaScript循环语句之for

015|JavaScript循环语句之for

作者: 中年小钢炮 | 来源:发表于2017-05-20 13:50 被阅读17次

上一节中,我们通过 while循环 解决了输出100次 “Hello World” 的问题。

为了方便开发者,JavaScript语言还提供一个方便开发者的 for循环语句

先来看一下 for循环 语法规则 :

for (init_statement; condition; after_statement){
    statement1;
    statement2;
    ... ...
}

while循环 一样,for循环 也有一个condition变量,它的作用与 while循环 中的condition一样。另外,for循环{}(花括号)中的多个 statement 语句其作用也和 while循环 一样。

不同的是,for循环 多了init_statement、after_statement两条语句。

下面给出 for循环 语法规则:

  1. 执行init_statemnt.
  2. 判断condition,如果为true,则跳转到3,否则,跳转到5。
  3. 执行循环体内的 statement1、statement2、...。
  4. 执行after_statement。跳转到2。
  5. 退出 for循环

现在,我们通过 for循环 来解决输出100次“Hello world”的需求。代码如下:

for (var count = 1; count <=100; count++)
{
    console.log("Hello world!")
}

我们再给出 while循环 的方案对比一下:

var count = 1 // for循环中的init_statement
while(count<=100)
{
    console.log("Hello world!")
    count++; // for循环中的after_statement
}

仔细观察可以发现,for循环while循环 中的有关循环次数控制的语句,都提取了出来成了init_statement、after_statement。

所以 for循环 使得开发者能够专注于处理condition为真的statement。另外,for循环结构清晰一些。

在实际开发工作中,while循环for循环 可以自由选择,没有硬性标准。

好了, 这一节讲到这里。for循环的基本内容,你学会了吗?

什么是 break 语句?
什么是 continue 语句?

请继续关注我的课程,我将在后续课程中为大家解答上述问题。

想学计算机技术吗?需要1对1专业级导师指导吗?想要团队陪你一起进步吗?欢迎加我为好友!

我的微信

相关文章

网友评论

      本文标题:015|JavaScript循环语句之for

      本文链接:https://www.haomeiwen.com/subject/svcpxxtx.html