#16 JS: loop - Part 1

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


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


<<:  [Day14] 学 Reactstrap 就离 React 不远了 ~ 用 Navbar 认识 useState

>>:  [Tableau Public] day 16:试着分析appstore资料集-1

资安学习路上-Linux基础与Web基础2

网站+网页绪论 浏览器介绍(推Firefox跟Edge) 上图取自台科大资安社课教材 浏览网页发生的...

D1: [漫画]工程师太师了-第1话

工程师太师了: 第1话 杂记: 本来打好主意每天来PO一张图,等我PO完30天,就可以完赛了。 今天...

bind9自建DNS解析服务

为了将来可能做DNS负载均衡、或故障转移等,先快速建一个简单的DNS服务,本次安装OS为Centos...

[Day 03] if条件、缩排规则、函式写法,以及一些字串技巧

[ 30 Days of ML Challenge | D03] 今天提供一个文件以及一个练习教材,...

Centos7安装seafile7.1.5专业版

Seafile 是一个开源的文件云存储平台,解决文件集中存储、同步、多平台访问的问,允许用户创建“群...