search
HomeWeb Front-endFront-end Q&AWhat are the program structures in javascript

What are the program structures in javascript

Jun 15, 2021 pm 05:26 PM
javascriptProgram structure

The program structure in JavaScript includes: 1. Sequential structure, which is executed sentence by sentence from beginning to end; 2. Branch structure, after reaching a certain node, it will decide which one to follow based on the result of a judgment. Branch direction execution; 3. Loop structure.

What are the program structures in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer

JavaScript program structure

The execution sequence of the program is divided into three types: sequential structure, branch structure and loop structure

1. Sequential structure

The default structure of the program is executed sentence by sentence from beginning to end

2. Branch structure (select structure)

To After a certain node, it will be decided based on the result of a judgment which branch direction to execute in the future

The characteristics of the branch structure: only one branch will be executed in the same branch structure

(1) if
if(条件){
代码块1;
}

Execution rules: If the condition is established, the code block corresponding to the if statement

var age = 26;
    if (age >= 18) {
   		alert("你已经成年");//你已经成年
    }

is executed in the same Only one branch will be executed in the branch structure. Because the two if conditions are independent, they will output

var a = 5;
       if (a > 3) {
           console.log(1);//1
       }
       if (a > 0) {
           console.log(2);//2
       }
2.if…else
if(条件){
	代码块1;
}else{
	代码块2;
}

Execution rules: if If the condition is true, the code block corresponding to the if statement is executed. If it is not true, the code block in else is executed.

var age = 15;
    if (age >= 18) {
   		alert("你已经成年");
   }else{
   		alert("你还没有成年");//你还没有成年
    }
3. Multi-branch statement
if(条件1){
	代码块1;
}else if(条件2){
	代码块2;
}
...
else if(条件n){
	代码块n;
}else{
	代码块m;
}

Execution rules : When condition n is met and the code block corresponding to condition n is executed, only one branch will be executed

var age = prompt('请输入年龄:');
        if (age < 18) {
            console.log(&#39;未成年&#39;);
        } else if (age >= 18 && age <= 30) {
            console.log(&#39;青年&#39;);
        } else if (age > 30 && age <= 60) {
            console.log(&#39;中年&#39;);
        } else if (age > 60) {
            console.log(&#39;老人&#39;)
        } else {
            console.log(&#39;请输入正确的年龄&#39;);
        }

[Related recommendations: javascript learning tutorial]

4.switch structure

switch...case is a congruent comparison

switch(表达式){
       case 值:
			代码块;
 			break;
		case 值2:
			代码块;
			break;
		...
		default:
			代码块;
			break
	}

Execution rules: The expression is compared with the value behind the case to determine whether the two Equal, if equal, the corresponding code block is executed. If the above case and expression are not equal, the content in default will be executed.

<script>
        var a = 10;
        var b = 20;
        var c = &#39;/&#39;;
        var result;
        switch (c) {
            case "+":
                result = a + b;
                break;
            case "-":
                result = a - b;
                break;
            case "*":
                result = a * b;
                break;
            case "/":
                result = a / b;
                break;
            default:
                result = a + b;
                break;
        }
        console.log(result);
    </script>

Switch penetration problem

 60分以上的及格,其他的留级        
 switch (score) {
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
                console.log(&#39;及格&#39;);
                break;
            default:
                console.log(&#39;留级&#39;);
                break;
        }

3. Loop structure

The loop structure has a loop body, and the loop body is a piece of code. For loop structures, the key is to decide how many times to execute the loop body based on the judgment result;

##1.for

for(循环变量初始化;循环判断;循环迭代){
	循环体;
}

Execution rules

  • Step 1: Loop variable initialization var i=0;

  • Step 2 : Loop condition judgment i The judgment is established Execute the loop body

    The judgment is not established End the loop

  • The third step: Loop iteration i

  • Step 4: Return to step 2

  •   for (var i = 0; i < 5; i++) {
                console.log(i);//0 1 2 3 4
            }

2.while

Execution rules: If If the condition is true, the loop body

while(条件){
		循环体;
	}
is executed to calculate how many times a piece of paper is folded, and the thickness exceeds Mount Everest


var total = 8848000;
        var h = 1;//纸厚度
        var count=0;
        while (h <= total) {            
            h*=2;
            count++;//次数递增
        }
        console.log(&#39;折叠了&#39;+count+&#39;次数&#39;);
        console.log(h);

3.do…while The difference between while and do...whiel: while loop will be judged first and then executed, do...while will be executed first and then judged. Regardless of whether the condition is true or false, it will be executed once

do{
	循环体;
 }while(条件);
 var a = 0;
        do {
            console.log(1);//1
        } while (a > 0);


        while (a > 0) {
            console.log(1);//无输出
            a++;
        }

4.for …in

Commonly used to traverse objects and arrays

数组
var arr = [10, 20, 30, 40];
for(var i in arr){
         console.log(i);
         console.log(arr[i]);
      }
对象
 var obj = {
            name: &#39;jack&#39;,
            age: &#39;20&#39;,
            addr: "北京路"
        };
        for (var i in obj) {
            console.log(i);
            console.log(i,obj[i]);
        }

5. The difference between break and continue

break; End the loop and leave yourself The nearest loop

continue; End this loop and continue the next loop, the loop closest to you

 for(var i=0;i<5;i++){
            if(i==2){
                break;
            }
            console.log(i);
        }
        var sum = 0;//需要有初值,否则会NaN
            if (i % 2 != 0) {
                continue;
            }
            sum += i;// sum =sum+0
        }

6. Nesting of loops

The outer loop is executed once, and the inner loop is executed once

 for (var j = 0; j < 4; j++) {
            //输出一行*
            for (var i = 0; i < 5; i++) {
                document.write(&#39;*&#39;);
            }
            //换行
            document.write("<br>");
        };

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of What are the program structures in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode PurposeReact Strict Mode PurposeApr 02, 2025 pm 05:51 PM

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.

React Fragments UsageReact Fragments UsageApr 02, 2025 pm 05:50 PM

React Fragments allow grouping children without extra DOM nodes, enhancing structure, performance, and accessibility. They support keys for efficient list rendering.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools