Home > Web Front-end > JS Tutorial > body text

A brief analysis of program control flow and functions in JavaScript

青灯夜游
Release: 2022-11-21 20:12:20
forward
1667 people have browsed it

This article will take you through the program control flow and functions in JavaScript. I hope it will be helpful to you!

A brief analysis of program control flow and functions in JavaScript

Mind Map

A brief analysis of program control flow and functions in JavaScript

?Program Control Flow

The operation of the program can be called the operation of "instruction flow", that is, the instructions of the program are flowing like water.

Program flow has 3 structures:

  • Sequential structure
  • Branch structure
  • Loop structure

⛳️Sequential structure

As the name suggests, the sequential structure means that the statements are written one by one in order, and when executed, they are executed in order. The most commonly used one is the assignment statement, for example, a=3; is an assignment statement - assign 3 to variable a.
An important concept related to assignment statements is expression. Each programming language will design a complete set of operators for first-level responses to several data types. Various types of literals, constants, and variables are organized together through operators to calculate a specific and unique result.

Case:

let a;
a=(4+5)*4;
const b=3*3;
Copy after login

The above code first declares a variable a, but it has not been assigned a value at this time, so its value is undefined. Then assign it a value through an expression, and its value becomes 36.
Next, a constant b is declared through the const keyword. const and let are very similar. The difference is that const declares a constant, that is, a quantity whose value can no longer be modified, while let declares a variable. Therefore, you must assign a value to a constant when you declare it, otherwise you cannot assign a value to it later.

⛳️Branch structure

The branch structure should be used for problems that require judgment first and then selection. The execution of the branch structure selects the execution path based on certain conditions, rather than strictly following the physical order in which statements appear. The key to the branch structure programming method is to construct appropriate branch conditions and analyze the program flow, and select appropriate branch statements according to different program flows. The branch structure is suitable for calculations with conditional judgments such as logical or relational comparisons. When designing such programs, it is often necessary to draw the program flow chart first, and then write the source program according to the program flow. In this way, the program design analysis and The separation of languages ​​makes the problem simple and easy to understand.

?Comparison operators

Comparison operators in JavaScript mainly include:

Equal to==
Strictly equal to===
Not equal to!=
Not strictly equal to!==
Greater than>
Greater than or equal to>=
Less than<
Less than or equal to<=

You can understand their meaning literally. A simple example is as follows:

Copy after login

The output of the above code is as follows:
true
false
true

Special note: Distinguish between == and === in JavaScript.

  • When using ==, if the types of the two comparison objects are not the same, the type will be converted first and then compared; if they are equal after conversion, then Return true.
  • When using ===, if the types of the two comparison objects are different, type conversion will not be performed and false will be returned directly.

#Comparison will only be performed if the types are the same, and true and false will be returned based on the comparison result.
Note:Currently, many software development teams have the simplest time regulations. In the actual development process, === is always used.

?Logical operators

The logical operators of javascript are:

  • Logical AND "&&", only returns true when both operands are true;

  • Logical OR "||" , if both operands are true, or one of them is true, return true;

  • Logical not "!", convert the value of the operand is a Boolean value and is inverted.
    A brief analysis of program control flow and functions in JavaScript

Example

Copy after login

The output results are as follows:
true
false
true
false

?if语句

  • if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码

语法:

if (condition)
{
    当条件为 true 时执行的代码
}
Copy after login

案例:如果时间早于 20:00,会获得问候 “Good day”。





if 语句

如果时间早于 20:00,会获得问候 "Good day"。

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript

  • if…else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码

语法:

if (condition)
{
    当条件为 true 时执行的代码
}
else
{
    当条件不为 true 时执行的代码
}
Copy after login

案例:当时间小于 20:00 时,生成问候 “Good day”:





if...else 语句

点击这个按钮,获得基于时间的问候。

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript

  • if…else if…else 语句- 使用该语句来选择多个代码块之一来执行

语法:

if (condition1)
{
    当条件 1 为 true 时执行的代码
}
else if (condition2)
{
    当条件 2 为 true 时执行的代码
}
else
{
  当条件 1 和 条件 2 都不为 true 时执行的代码
}
Copy after login

案例:如果时间小于 10:00,则生成问候 “Good morning”,如果时间大于 10:00 小于 20:00,则生成问候 “Good day”,否则生成问候 “Good evening”。




if...else if....else 语句

这个例子演示了 if..else if...else 语句。

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript

?switch语句

当需要判断的情况比较多的时候,通常采用switch语句来实现

语法:

switch(n)
{
    case 1:
        执行代码块 1
        break;
    case 2:
        执行代码块 2
        break;
    default:
        与 case 1 和 case 2 不同时执行的代码
}
Copy after login

工作原理:首先设置表达式 n(通常是一个变量)。随后表达式的值会与结构中的每个 case 的值做比较。如果存在匹配,则与该 case 关联的代码块会被执行。请使用 break 来阻止代码自动地向下一个 case 运行。

案例:显示今天的星期名称。请注意 Sunday=0, Monday=1, Tuesday=2, 等等:





switch语句

点击下面的按钮来显示今天是周几:

Copy after login

运行效果:
A brief analysis of program control flow and functions in JavaScript

⛳️循环结构

循环结构的作用是反复执行同一段代码。尽管循环结构可分为几种不同的类型,但是他们的基本原理都是一样的。只要给定的条件仍能得到满足,包含在循环体里的代码就会重复执行下去,一旦条件不再满足则终止。在JavaScript中有三种循环结构,while、do…while、for循环。它们都含有初始值,循环条件,循环操作迭代部分

?while语句

while 循环会在指定条件为真时循环执行代码块。

语法:

while (条件)
{
    需要执行的代码
}
Copy after login

案例:本例中的循环将继续运行,只要变量 i 小于 5;





while语句

点击下面的按钮,只要 i 小于 5 就一直循环代码块。

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript

?do…while语句

do/while 循环是 while 循环的变体。该循环会在检查条件是否为真之前执行一次代码块,然后如果条件为真的话,就会重复这个循环。

语法

do
{
    需要执行的代码
}
while (条件);
Copy after login

案例:如上





do...while语句

点击下面的按钮,只要 i 小于 5 就一直循环代码块。

Copy after login

运行结果
A brief analysis of program control flow and functions in JavaScript

?for语句

for语句是前测试循环语句,也称for循环,进入循环之前能够初始化变量,并且能够定义循环后要执行的代码。

语法:

for (语句 1; 语句 2; 语句 3)
{
    被执行的代码块
}
Copy after login

语句 1 (代码块)开始前执行
语句 2 定义运行循环(代码块)的条件
语句 3 在循环(代码块)已被执行之后执行

案例:点击按钮循环代码5次。





for语句

点击按钮循环代码5次。

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript

?break和continue语句

break 语句用于跳出循环,阻止程序再次运行循环体中的任何代码。

continue 用于跳过循环中的一个迭代,即当前循环,根据控制表达式还允许进行下一次循环。

break 语句示例:点击按钮,测试带有 break 语句的循环。





break 语句

点击按钮,测试带有 break 语句的循环。

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript
continue 语句示例:循环跳过 i=3 的数字。





continue 语句

点击下面的按钮来执行循环,该循环会跳过 i=3 的数字。

Copy after login

运行效果:
A brief analysis of program control flow and functions in JavaScript

?for…of语句

在ES6中引入了一个心的概念——“迭代器”。数组或其他集合类的对象内部都实现了迭代器,从而可以更方便地遍历其中的元素。在实际开发中,大多数需要对数组元素进行循环处理的场景,采用for…of语句都会比使用传统的for语句更方便。

案例:假设在一个数组中记录了所有团队成员的名字:
let team=[“Tom”,“Mike”,“Jane”];
现在需要将所有成员两两配对,组成二人小组,每组由一个组长及一个组员组成。那么如何求出所有可能的二人小组呢?

方法一:传统for循环实现(二重for循环)

let pairs=[]; //用于保存最终的结果
for(let i=0;i
Copy after login

方法二:使用for…of迭代器

let pairs=[]; //用于保存最终的结果
for(let a of team){
	for(let b of team){
		if(a!=b)
			pairs.push([a,b]);
	}
}
Copy after login

?for…in语句

通常用来枚举对象的属性,但是到目前为止我们还没有真正讲解对象和属性的支持,所以只能做一点简单的介绍。for…in语句的作用是遍历一个对象的所有属性。

语法:

for(property in expression) statement
Copy after login

它将遍历expression对象中的所有属性,并且每一个属性都执行一次statement循环体。

案例:遍历显示window对象的所有属性





    
    
    
    Document

Copy after login

运行效果:
A brief analysis of program control flow and functions in JavaScript

?函数

函数是一组可以随时随地运行的语句。简单来说,函数是完成某个功能的一组语句,或者说是一组语句的封装。它可以接收0个或多个参数,然后执行函数体来完成某些功能,最优根据需要返回或者不返回处理结果。

JavaScript 函数语法
函数就是包裹在花括号中的代码块,前面使用了关键词 function:

function functionname()
{
    // 执行代码
}
Copy after login

当调用该函数时,会执行函数内的代码。

可以在某事件发生时直接调用函数(比如当用户点击按钮时),并且可由 JavaScript 在任何位置进行调用。

注意:JavaScript 对大小写敏感。关键词 function 必须是小写的,并且必须以与函数名称相同的大小写来调用函数。

调用带参数的函数
在调用函数时,您可以向其传递值,这些值被称为参数。

这些参数可以在函数中使用。

您可以发送任意多的参数,由逗号 (,) 分隔:
myFunction(argument1,argument2)

当您声明函数时,请把参数作为变量来声明:

function myFunction(var1,var2)
{
	代码
}
Copy after login

案例:


	
 
 
带参数的函数 

点击这个按钮,来调用带参数的函数。

Copy after login

运行效果:

A brief analysis of program control flow and functions in JavaScript

带有返回值的函数
有时,我们会希望函数将值返回调用它的地方。
通过使用 return 语句就可以实现。
在使用 return 语句时,函数会停止执行,并返回指定的值。

语法

function myFunction()
{
    var x=5;
    return x;
}
Copy after login

上面的函数会返回值 5。

注意: 整个 JavaScript 并不会停止执行,仅仅是函数。JavaScript 将继续执行代码,从调用函数的地方。

函数调用将被返回值取代:
var myVar=myFunction();
myVar 变量的值是 5,也就是函数 “myFunction()” 所返回的值。

即使不把它保存为变量,您也可以使用返回值:
document.getElementById(“demo”).innerHTML=myFunction();
“demo” 元素的 innerHTML 将成为 5,也就是函数 “myFunction()” 所返回的值。
您可以使返回值基于传递到函数中的参数:

案例:计算两个数字的乘积,并返回结果



 
 
乐趣国学 

本例调用的函数会执行一个计算,然后返回结果:

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript
局部 JavaScript 变量
在 JavaScript 函数内部声明的变量(使用 var)是局部变量,所以只能在函数内部访问它。(该变量的作用域是局部的)。

您可以在不同的函数中使用名称相同的局部变量,因为只有声明过该变量的函数才能识别出该变量。

只要函数运行完毕,本地变量就会被删除。

全局 JavaScript 变量
在函数外声明的变量是全局变量,网页上的所有脚本和函数都能访问它。

JavaScript 变量的生存期
JavaScript 变量的生命期从它们被声明的时间开始。
局部变量会在函数运行以后被删除。
全局变量会在页面关闭后被删除。

?异常处理

try 语句测试代码块的错误。

catch 语句处理错误。

throw 语句创建自定义错误。

finally 语句在 try 和 catch 语句之后,无论是否有触发异常,该语句都会执行。

JavaScript 抛出(throw)错误
当错误发生时,当事情出问题时,JavaScript 引擎通常会停止,并生成一个错误消息。
描述这种情况的技术术语是:JavaScript 将抛出一个错误。

try 和 catch
try 语句允许我们定义在执行时进行错误测试的代码块。
catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块。
JavaScript 语句 try 和 catch 是成对出现的。

语法

try {
    ...    //异常的抛出
} catch(e) {
    ...    //异常的捕获与处理
} finally {
    ...    //结束处理
}
Copy after login

案例:





乐趣国学


Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript

finally 语句
finally 语句不论之前的 try 和 catch 中是否产生异常都会执行该代码块。

案例





乐趣国学

不管输入是否正确,输入框都会再输入后清空。

请输入 5 ~ 10 之间的数字:

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript
Throw 语句
throw 语句允许我们创建自定义错误。
正确的技术术语是:创建或抛出异常(exception)。
如果把 throw 与 try 和 catch 一起使用,那么您能够控制程序流,并生成自定义的错误消息。

语法
throw exception

异常可以是 JavaScript 字符串、数字、逻辑值或对象。

案例:本例检测输入变量的值。如果值是错误的,会抛出一个异常(错误)。catch 会捕捉到这个错误,并显示一段自定义的错误消息:





乐趣国学

请输出一个 5 到 10 之间的数字:

Copy after login

运行结果:
A brief analysis of program control flow and functions in JavaScript

【推荐学习:javascript高级教程

The above is the detailed content of A brief analysis of program control flow and functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!