JavaScript Loops

Different Kinds of Loops

JavaScript supports different kinds of loops:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

The For Loop

The for loop is often the tool you will use when you want to create a loop.

The for loop has the following syntax:

for ( statement 1; statement 2; statement 3)   {   the code block to be executed   }

Statement 1 is executed before the loop (the code block)  starts.

Statement 2 defines the condition for running the loop (the code block).

Statement 3 is executed each time after the loop (the code block) has been executed.

The For/In Loop

The JavaScript for/in statement loops through the properties of an object:

Example

var person={fname:"John",lname:"Doe",age:25}; 

 for (x in person)
   {
   txt=txt + person[x];
   }

The While Loop

The while loop loops through a block of code as long as a specified condition is true.

Syntax

while (condition)
   {
  code block to be executed
   }

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will  execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do
   {
  code block to be executed
   }
 while (condition);

 

 

转载于:https://www.cnblogs.com/Linford-Xu/archive/2013/05/08/3066663.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值