Table of Contents
1. Make a judgment (if statement)
2. Choose one of the two (if...else statement)
3. Multiple judgments (if..else if..nested statements)
4. Multiple choices (Switch..case statement)
5. Repeat (for loop)
6. Repeatedly (while loop)
7. Back and forth (Do...while loop)
8.for...in statement: Loop through the properties of the object
9.for...of语句: 循环遍历对象的属性
10.退出循环break
11.跳过本次循环continue
Home Web Front-end JS Tutorial What are the statements for javascript flow control?

What are the statements for javascript flow control?

Oct 09, 2021 pm 04:16 PM
javascript process control

Flow control statements include: 1. if statement; 2. "if...else" statement; 3. "if..else if.." nested statement; 4. "Switch..case" statement; 5. for statement; 6. while statement; 7. "do...while" statement; 8. "for..in", etc.

What are the statements for javascript flow control?

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

1. Make a judgment (if statement)

The if statement is a statement used to execute the corresponding code based on the condition being established.

Grammar:

if(条件)
{
 条件成立时执行代码
}
Copy after login

Note: If lowercase, uppercase letters (IF) will cause errors!

Suppose you apply for a web front-end technology development position. If you know HTML technology and you succeed in the interview, you are welcome to join the company. The code is expressed as follows:

<script type="text/javascript">
  var mycarrer = "HTML";
  if (mycarrer == "HTML")
  {
    document.write("你面试成功,欢迎加入公司。");
  }
</script>
Copy after login

2. Choose one of the two (if...else statement)

The if...else statement is to execute the code when the specified condition is true, and when the condition is not true Code after executing else.

Grammar:

if(条件)
{ 条件成立时执行的代码}
else
{条件不成立时执行的代码}
Copy after login

Suppose you apply for a web front-end technology development position. If you know HTML technology and your interview is successful, you are welcome to join the company. Otherwise, your interview will be unsuccessful and you will not be able to join the company.

The code is expressed as follows:

<script type="text/javascript">
  var mycarrer = "HTML"; //mycarrer变量存储技能
  if (mycarrer == "HTML")
    { document.write("你面试成功,欢迎加入公司。");  }
  else  //否则,技能不是HTML
    { document.write("你面试不成功,不能加入公司。");}
</script>
Copy after login

3. Multiple judgments (if..else if..nested statements)

To select one group of multiple groups of statements to execute, use if..else if..nested statements.

Grammar:

if(条件1)
{ 条件1成立时执行的代码}
else  if(条件2)
{ 条件2成立时执行的代码}
...
else  if(条件n)
{ 条件n成立时执行的代码}
else
{ 条件1、2至n不成立时执行的代码}
Copy after login

4. Multiple choices (Switch..case statement)

When there are many options When using switch, switch is more convenient than if else.

Grammar:

switch(表达式){case值1:
  执行代码块 1  break;case值2:
  执行代码块 2  break;...case值n:
  执行代码块 n  break;default:
  与 case值1 、 case值2...case值n 不同时执行的代码
}
Copy after login

Grammar description:

Switch must be assigned an initial value, and the value is the same as each case value matches.
Satisfy all statements after executing the case, and use the break statement to prevent the next case from running.
If all case values ​​do not match, execute the statement after default.

Assuming that students' test scores are evaluated on a 10-point full-score system, we grade the scores according to each grade and make different evaluations based on the grade of the scores.

Note: Remember to add a break statement after the statement executed by the case. Otherwise, just continue to execute the statement in the case below. Look at the following code:

5. Repeat (for loop)

Many things are not just done once, but done repeatedly. For example, print 10 copies of the test paper, one at a time, and repeat this action until the printing is completed. We use loop statements to accomplish these things. A loop statement is to repeatedly execute a piece of code.

forStatement structure:

for(初始化变量;循环条件;循环迭代)
{     
    循环语句 
 }
Copy after login

If there are 6 balls in a box, we take one ball at a time and repeatedly take it out from the box ball until all the balls are taken.

<script type="text/javascript">
var num=1;
for (num=1;num<=6;num++)  //初始化值;循环条件;循环后条件值更新
{   document.write("取出第"+num+"个球<br />");
}
</script>
Copy after login

6. Repeatedly (while loop)

The while loop has the same function as the for loop. The while loop repeatedly executes a piece of code until a certain condition is no longer met.

whileStatement structure:

while(判断条件){
    循环语句
 }
Copy after login

Use a while loop to complete the action of taking the ball from the box, one at a time, a total of 6 ball.

<script type="text/javascript">
var num=0;  //初始化值
while (num<=6)   //条件判断
{
  document.write("取出第"+num+"个球<br />");
  num=num+1;  //条件值更新
}
</script>
Copy after login

7. Back and forth (Do...while loop)

The basic principle of the do while structure is basically the same as the while structure, but it guarantees that the loop body is executed at least once. Because it executes the code first, then judges the condition. If the condition is true, the loop continues.

do...whileStatement structure:

do{
    循环语句
 }while(判断条件)
Copy after login

We try to output 5 numbers.

<script type="text/javascript">
   num= 1;
   do
   {
     document.write("数值为:" +  num+"<br />");
     num++; //更新条件
   }
   while (num<=5)
</script>
Copy after login

8.for...in statement: Loop through the properties of the object

The for in loop is a special type of loop and a variant of the ordinary for loop, mainly used to traverse Object, which can be used to cycle out the attributes in the object in sequence. The syntax format is as follows:

for (variable in object) {
    // 要执行的代码
}
Copy after login

Among them, variable is a variable, which will be assigned a different value each time it is looped. We can { } Use this variable to perform a series of operations; object is the object to be traversed. In each loop, the key of an attribute in the object object will be assigned to the variable variable until all attributes in the object have been traversed.

JS for in 循环示例代码:

// 定义一个对象
var person = {"name": "Clark", "surname": "Kent", "age": "36"};
// 遍历对象中的所有属性
for(var prop in person) {
    document.write("<p>" + prop + " = " + person[prop] + "</p>");
}
Copy after login

运行结果:

name = Clark
surname = Kent
age = 36
Copy after login

9.for...of语句: 循环遍历对象的属性

for of 循环是 ECMAScript6 中新添加的一个循环方式,与 for in 循环类似,也是普通 for 循环的一种变体。使用 for of 循环可以轻松的遍历数组或者其它可遍历的对象,例如字符串、对象等。

JS for of 循环的语法格式如下:

for (variable of iterable) {
    // 要执行的代码
}
Copy after login

其中,variable 为一个变量,每次循环时这个变量都会被赋予不同的值,我们可以在后面的{ }中使用这个变量来进行一系列操作;iterable 为要遍历的内容,在每次循环中,会将 iterable 中的一个值赋值给变量 variable,直到 iterable 中的所有值都遍历完。

示例代码如下:

// 定义一个数组
var arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;];
// 使用 for of 循环遍历数组中的每个元素
for (var value of arr) {
    document.write(value + ", ");
}
document.write("<br>");
// 定义一个字符串
var str = "Hello World!";
// 使用 for of 循环遍历字符串中的每个字符
for (var value of str) {
    document.write(value + ", ");
}
document.write("<br>");
// 定义一个对象
var obj = {"name": "Clark", "surname": "Kent", "age": "36"};
// 使用 for of 循环遍历对象中的所有属性
for(var value in obj) {
    document.write(value + ", ");
}
Copy after login

运行结果:

a, b, c, d, e, f,
H, e, l, l, o, , W, o, r, l, d, !,
name, surname, age,
Copy after login

10.退出循环break

在while、for、do...while、while循环中使用break语句退出当前循环,直接执行后面的代码。

格式如下:

for(初始条件;判断条件;循环后条件值更新)
{  if(特殊情况)
  {break;}
  循环代码
}
Copy after login

当遇到特殊情况的时候,循环就会立即结束。看看下面的例子,输出10个数,如果数值为5,就停止输出。

11.跳过本次循环continue

continue的作用是仅仅跳过本次循环,而整个循环体继续执行。

语句结构:

for(初始条件;判断条件;循环后条件值更新)
{
  if(特殊情况)
  { continue; }
 循环代码
}
Copy after login

上面的循环中,当特殊情况发生的时候,本次循环将被跳过,而后续的循环则不会受到影响。

【推荐学习:javascript高级教程

The above is the detailed content of What are the statements for javascript flow control?. For more information, please follow other related articles on the PHP Chinese website!

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What are the common process control structures in Python? What are the common process control structures in Python? Dec 12, 2023 pm 04:31 PM

There are three common process control structures in python, namely sequence structure, selection structure and loop structure. Detailed introduction: 1. Sequential structure, which is the simplest structure in the program. According to the order of the code, it is executed from top to bottom; 2. Selection structure, this structure can be judged according to certain conditions and choose to execute different codes. Blocks, in Python, usually use "if-elif-else" statements to implement selection structures; 3. Loop structures, which can repeatedly execute a piece of code until it stops when a certain condition is met, etc.

See all articles