iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0

while statement

If the statement is true, the code inside of {} would be executed.
When the first execution is done, the system will return to the while to repeat the execution.
The loop will stop until the result becomes false.

var n=0;
while(n<=50) {
    n++;
}
alert(n);
 
var sum=0;
var i=1;
while(i<=100){
    sum=sum+i; → it can be written as sum+=i as well.
    i++;
}
alert(sum);

for statement

  • The concept of while and for is similar, but for combines 3 important blocks together, which makes the code simpler.
  • Each of the statement means: for(initialization command;statement for decide whether the next loop continues;execute after every loop){
    }
var sum=0;
for(var i=1;i<=100;i++){
    sum=sum+i;
}
alert(sum);

break & continue

  • break; → "jumps out" of a loop (強制跳出迴圈)
  • continue; → "jumps over" one iteration in the loop (強制進行下一次的迴圈)
    by W3C Schools

Example 1. while statement x break

var n=0
while(n<=100){
    if(n==50){
        break;
    }
    n++;
}
alert(n); 

=>n is 50.

Example 2. for statement x continue

var x=0;
for(var n=0;n<=100;n++){
    if(n%4==0){ → n can be divided exactly by 4.
        continue;
    }
    x++;
}
alert(x);

=>x is 75.


Music of Today: When You Wish Upon A Star by Joey Alexander

Yes


Like/Share/Follow

Feel free to comment and share your ideas below to learn together!
If you guys find this article helpful, please kindly do the writer a favor — LIKE this article./images/emoticon/emoticon12.gif


上一篇
#15 JS: if else statement
下一篇
#17 JS: loop - Part 2
系列文
Learn & Play JavaScript -- Entry-Level Front-End Web Development30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言