Detailed explanation of JavaScript program loop structure

Detailed explanation of JavaScript program loop structure

Select Structure

Single branch if structure

if(condition){
Code executed after the condition is met}

If there is only one statement in the curly braces, you can omit the curly braces, but this is strongly not recommended.

if(condition)
	console.log('dot dot dot')

Two-branch if structure statement

if (condition) {
Code executed after the condition is met}
else{
Code executed if the condition is not met}

Multi-branch if structure statement

if(condition 1){
Code 1
}
else if(condition 2){
Code 2
}
......
else{
None of the above conditions are met and the code is executed}

Switch Structure

var today=1
switch(today){
	case 1:
		console.log('working day')
		break
	case 2:
		console.log('working day')
		break
	case 3:
	case 4:
	case 5:
		console.log('working day')
		break
	default
		console.log('rest day')
		break

The difference between switch and if

  • switch can only perform equal value judgment if
  • There is no restriction on the judgment of a continuous interval.

Loop Structure

Repeated execution of an operation is called a loop.

while

//Loop 10 times var i=1
while(i<=10){
console.log('111111')
i++
}
//Example: Calculate the sum of integers within 100 var i=1
var sum = 0
while(i<=100){
 sum+=i
 i++
}
Example: Output all integers between [1,200] that are divisible by 7 but not by 4, and count the number of them. At the same time, the output requires 5 var i=1 to be displayed on each line.
var count = 0
while(i<=200){
	if(i%7==0 && i%4!=0){
		document.write(i+"&nbsp;&nbsp;&nbsp;&nbsp;")
		count++; //Count the number // Determine if 5 outputs are changed to a new line if (count%5==0){
		document..write('<br>');
		}
	}
	i++;
	document.write('<br>Total: '+count+'')

do … while

Execute the code first, then judge the condition

var i=1;
        do{
            console.log('Study hard and make progress every day!')
            i++;
        }while(i<=10)
  #Case#Calculate the multiple between 1-50<script type="text/javascript">
        var i=1;
        var sum=0;
        do{
            if(i%6==0){
                sum+=i
            }
            i++;
        }while(i<=50)
        console.log(sum)
    </script>
#Case# Loop to prompt the user to enter 5 numbers, press q to end, and then output the maximum and minimum values ​​#Prompt the user to enter once, then use the number as the maximum and minimum values ​​var num = Number(prompt('Please enter a characteristic (press q to end):'))
 var max=num;
var min=num;
var flag = true // Indicates whether to continue the loop var i = 1;
do{
var num=Number(promot('Please enter an integer!'))
#Determine whether the user enters q
if(num=='q'){
flag=false //If you enter q, change flag to false, indicating that the loop stops}else{
num=Number(num)
if(num>max){
	max=num;
}
if (num<min){
min=num
}
}while(flag)
console.log(max)
console.log(min)

for loop

grammar

for(initialization:condition:iteration){
Code Block}

The initialization part is executed first at the beginning of the loop, and the initialization part is executed only once

After the initialization is completed, it is determined whether the condition is met. If so, the code block is executed, and then the iteration part is executed.

for … in …

Traverse the collection data

The loop traversal is the index order of the traversed data in the collection (starting from 0), not the data itself

<script type="text/javascript">
        var str = 'abc'
        for(var index in str){
            console.log(index,str[index])
        }
    </script>

insert image description here

for …of…

Iterate over the collection data

This is to get the value directly

<script type="text/javascript">
        var str = 'abc'
        for(var index of str){
            console.log(index)
        }
    </script>

insert image description here

summary

  • When the number of loops is determined, for is generally used
  • When the number of loops is uncertain, while and do...while are generally used
  • Use for...in and for...of to iterate over a collection

Terminating the loop

break

break jumps out of the entire loop and terminates the execution of the loop

Case

//When integers between 1 and 20 are added, stop adding when the accumulated value is greater than 66, and output the current integer and the accumulated value var sum = 0
for(var i=1;i<=20;i++){
	sum+=1
	if(sum>66){
	break
}
}

continue

Jump out of this loop and execute the next loop. This loop has not yet been completed.

//Calculate the sum of all even numbers between 1-10 var sum=0;
for(var i=1;i<=10;i++){
	if(i%2!=0){
	continue
	}
	sum+=i
}

Second layer cycle

A loop is nested in another loop, forming a double loop. Various loops can be nested in each other.

The outer loop variable changes once, and the inner loop executes once

//Case //In a certain programming competition, there are three classes participating, each with 4 students. Enter the scores of each student in each class, and then calculate the average score of each class for(var i=1;i<=3;i++){
	alert('Please enter the student information of the '+i+'th class---')
	//Inner loop controls the number of students in the class var sum=0
	for(var j=1;j<=4;j++){
	var score=Number(prompt('Please enter the score of the '+j+'th student:'))
	sum+=score;
}
	console.log('The average score of the '+i+'th class is: '+sum/4)
}
  <script type="text/javascript">
        for(var i=1;i<=9;i++){
            for(var j=1;j<=i;j++){
                document.write(j+'*'+i+'='+i*j+'&nbsp;&nbsp')
            }
            document.write('<br>')
        }
    </script>

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • JS basics: logical structure and loop operation examples
  • Implementation of bidirectional linked list and bidirectional circular linked list in JavaScript data structure
  • JavaScript data structure: singly linked list and circular linked list
  • Detailed explanation of JavaScript data structure: priority queue and circular queue examples
  • Simple learning of the for statement loop structure in JavaScript

<<:  Radio buttons and multiple-choice buttons are styled using images

>>:  Sample code for displaying reminder dots in the upper left or upper right corner using CSS3

Recommend

Tutorial on installing MYSQL8.0 on Alibaba Cloud ESC

Open the connection tool. I use MobaXterm_Persona...

Detailed explanation of pid and socket in MySQL

Table of contents 1. Introduction to pid-file 2.S...

UTF-8 and GB2312 web encoding

Recently, many students have asked me about web p...

How to install mysql via yum on centos7

1. Check whether MySQL is installed yum list inst...

Free tool to verify that HTML, CSS and RSS feeds are correct

One trick for dealing with this type of error is t...

Detailed installation and uninstallation tutorial for MySQL 8.0.12

1. Installation steps for MySQL 8.0.12 version. 1...

Detailed explanation of linux nslookup command usage

[Who is nslookup?] 】 The nslookup command is a ve...

Bootstrap 3.0 study notes grid system case

Preface In the previous article, we mainly learne...

Steps to configure nginx ssl to implement https access (suitable for novices)

Preface After deploying the server, I visited my ...

KVM virtualization installation, deployment and management tutorial

Table of contents 1.kvm deployment 1.1 kvm instal...

Mini Program to Implement Calculator Function

This article example shares the specific code of ...

How to use Docker-compose to deploy Django applications offline

Table of contents Install Docker-ce for the devel...

Analysis of the cause of docker error Exited (1) 4 minutes ago

Docker error 1. Check the cause docker logs nexus...

How to install Postgres 12 + pgadmin in local Docker (support Apple M1)

Table of contents introduce Support Intel CPU Sup...