- Chinese version of TypeScript Tutorial – Project introduction
- TypeScript Tutorial Chinese version – Section 0. preface
- TypeScript Tutorial Chinese version – Section 1. An introduction to
- TypeScript Tutorial Chinese version – Section 2. Basic types of
- TypeScript Tutorial Chinese version – Section 3. Control flow statement
- TypeScript Tutorial Chinese – Section 4. function
- TypeScript Tutorial Chinese version – Section 5. class
- TypeScript Tutorial Chinese version – Section 6. interface
- TypeScript Tutorial Chinese version – Section 7. High-level types
- TypeScript Tutorial Chinese version – Section 8. The generic
- TypeScript Tutorial Chinese version – Section 9. The module
- Chinese version of TypeScript Tutorial – Section 10.node.js
Section 3. Control flow statements
if else
The original address
In this tutorial, you’ll learn about if else statements in TypeScript.
If statements in TypeScript
The if statement determines whether to execute the statement based on whether the condition is true or false. If the condition is true, the if statement executes the statement in the body:
if (condition) {
// if-statement
}
Copy the code
The following example demonstrates how to use the if statement to increment the value of the counter variable if the value of the counter variable is less than the value of the Max variable:
const max = 100;
let counter = 0;
if (counter < max) {
counter++;
}
console.log(counter); / / 1
Copy the code
Output:
1
Copy the code
In this example, because the counter variable has an initial value of 0, which is smaller than the value of the Max constant, the expression counter < Max has a value of true, so the if statement will execute Counter ++. Let’s initialize the value of the counter variable to 100:
const max = 100;
let counter = 100;
if (counter < max) {
counter++;
}
console.log(counter); / / 100
Copy the code
Output:
100
Copy the code
In this example, the expression counter < Max evaluates to false, so the if statement does not execute counter++, so the output is 100.
If else statements in TypeScript
If you want to execute other statements when the condition evaluates to false, you can use the if else statement:
if (condition) {
// if-statements
} else {
// else statements;
}
Copy the code
Here is an example of using an if else statement:
const max = 100;
let counter = 100;
if (counter < max) {
counter++;
} else {
counter = 1;
}
console.log(counter);
Copy the code
Output:
1
Copy the code
In this example, the counter < Max expression evaluates to false, so the statement in the else branch executes, setting the counter variable to 1.
Ternary operators? :
In practice, if it’s just a simple conditional judgment, you can use the ternary operator, right? : replaces the if else statement to make the code look shorter and easier to understand, like this:
const max = 100;
let counter = 100;
counter < max ? counter++ : (counter = 1);
console.log(counter);
Copy the code
If else if else statement
To execute multi-conditional branching statements, use the if else if else statement. If else If else statements can have one or more else if branches, but only one else branch, as shown below:
let discount: number;
let itemCount = 11;
if (itemCount > 0 && itemCount <= 5) {
discount = 5; // 5% discount
} else if (itemCount > 5 && itemCount <= 10) {
discount = 10; // 10% discount
} else {
discount = 15; / / 15%
}
console.log(`You got ${discount}% discount. `);
Copy the code
Output:
0
Copy the code
This example uses the if else if else statement to determine discounts based on the value of the items variable:
- if
items
The value of a variable is less than or equal to5
When, then the discount is5%
.if
Branch statement execution; - if
items
The value of a variable is less than or equal to10
When, then the discount is10%
.else if
Branch statement execution; - when
items
The value of the variable is greater than10
When, then the discount is15%
.else
Branch statement execution.
In this example, we assume that the value of the items variable is always greater than 0, and that the discount is 10% if the value of the items variable is less than 0 or greater than 10. To make the code more robust, we can add an else if branch before the else branch, as shown below:
let discount: number;
let itemCount = 11;
if (itemCount > 0 && itemCount <= 5) {
discount = 5; // 5% discount
} else if (itemCount > 5 && itemCount <= 10) {
discount = 10; // 10% discount
} else if (discount > 10) {
discount = 15; / / 15%
} else {
throw new Error('The number of items cannot be negative! ');
}
console.log(`You got ${discount}% discount. `);
Copy the code
In this case, the discount is 10% only if the items variable is greater than 10, and the second else if branch is executed. If the value of the items variable is less than 0, the else branch executes.
summary
- use
if
Statement to decide whether to execute a statement based on whether the condition is true or false; - use
else
Branch when you want to in condition forfalse
Execute some code while using ternary operators? :
Instead ofif else
Statements are a good practice; - use
if
else if
else
Statement A statement that executes a multi-conditional branch.
switch case
The original address
In this tutorial, you will learn about switch Case statements in TypeScript
Switch Case statements in TypeScript
Here is the syntax for the switch case statement:
switch (expression) {
case value1:
// statement 1
break;
case value2:
// statement 2
break;
case valueN:
// statement N
break;
default:
//
break;
}
Copy the code
Here’s how it works:
- First of all,
switch case
Statement to calculateexpression
The value of the; - It then searches for the first calculated value (
value1
.value2
和valueN
And so on) andexpression
That’s the same valuecase
Clauses.
The switch case statement executes the statement in the first matching case clause. If no matching case clause is found, the Switch case statement looks for the optional default clause, and if the default clause is available, it executes the statement in the default clause.
The break statement associated with each case clause ensures that it exits the switch case statement when the statement in the case clause has finished executing. If the matching case clause does not have a break statement, the program continues with the statement following the switch case statement.
By convention, the default clause is the last clause in a Switch case statement, but it is not mandatory.
Switch Case statement example
Let’s look at some examples of switch case statements
1) A simple switch case example
Here is a simple switch case that displays different information based on the value of targetId:
let targetId = 'btnDelete';
switch (targetId) {
case 'btnUpdate':
console.log('Update');
break;
case 'btnDelete':
console.log('Delete');
break;
case 'btnNew':
console.log('New');
break;
}
Copy the code
Output:
Delete
Copy the code
In this example, the targetId is assigned to btnDelete. The switch case statement compares targetId with a set of values, and since targetId matches ‘btnDelete’, the statement in the corresponding case clause is executed.
2) Case group cases
If you want a piece of code to be shared by multiple cases, you can group them as follows:
// change the month and year
let month = 2,
year = 2020;
let day = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
case 2:
// leap year
if ((year % 4= =0 && !(year % 100= =0)) || year % 400= =0) day = 29;
else day = 28;
break;
default:
throw Error('Invalid month');
}
console.log(`The month ${month} in ${year} has ${day} days`);
Copy the code
Output:
The month 2 in 2020 has 29 days
Copy the code
This case returns the number of days in the specified year and month:
- If the month is
1
3
5
7
8
10
or12
, the returned days are31
; - If the month is
4
6
9
or11
, the returned days are30
天 - If the month is
2
If it is a leap year, return29
Day, otherwise return28
Days.
for
The original address
In this tutorial, you’ll learn about the for statement in TypeScript, which executes a piece of code repeatedly.
Introduction to the for statement in TypeScript
Here’s the syntax for a TypeScript for loop:
for (initialization; condition; expression) {
// statement
}
Copy the code
The for loop is wrapped in parentheses, with a semicolon (;). Separated by three optional expressions:
initialization
– Expressions executed before loops are usually executed ininitialization
The value of the initial cycle counter in;condition
– The expression executed at the end of each iteration of the loop, ifcondition
The calculated result istrue
.for
Loop statements continue to execute statements in the body of the loop;expression
– in the implementationcondition
An expression executed before a statement is usually executed in theexpression
Update the value of the loop calculator in.
All three expressions in the for loop are optional, which means it can be used like this:
for (;;) {
// do something
}
Copy the code
In practice, you should use the for loop if you know how many times the loop is executed, and the while loop if you need to decide whether to stop the loop based on conditions other than the number of times the loop is executed.
TypeScript allows you to omit the body of a for loop completely, like this:
for (initialization; condition; expression);
Copy the code
But in practice it is rarely used this way, making the code difficult to read and maintain.
Loop example
Let’s look at a few examples of using TypeScript for loops:
1) Simple for loop example
The following example uses a for loop to print 10 numbers between 0 and 9:
for (let i = 0; i < 10; i++) {
console.log(i);
}
Copy the code
Output:
0
1
2
3
4
5
6
7
8
9
Copy the code
Here’s how it works:
- First of all, it’s declared
i
Variable, and initialize its value to0
; - check
i
Is the value of10
Small, if yes, print its value to the console and givei
Variable plus one; - Finally, loop the second step until
i
The value is equal to the10
, end the loop.
2) For loop example: optional expression
The following example has the same output as the above example, but the following for loop has no initialization expression:
let i = 0;
for (; i < 10; i++) {
console.log(i);
}
Copy the code
As with the initialization expression, you can omit the condition expression. But you must use an if or break statement to terminate the loop when certain conditions are met, otherwise you will create an infinite loop, causing the program to repeat itself until it crashes:
for (let i = 0; ; i++) {
console.log(i);
if (i > 9) break;
}
Copy the code
The following example demonstrates a for loop that omits three expressions:
let i = 0;
for (;;) {
console.log(i);
i++;
if (i > 9) break;
}
Copy the code
Output:
0
1
2
3
4
5
6
7
8
9
Copy the code
Here’s how it works:
- First, in the entry
for
One is declared before the loop statementi
Loop through the counter and initialize its value to0
; - And then, on each iteration of the loop, put the
i
Output to the console and increment its value by one to determine ifi
The value is greater than9
If so, break out of the loop.
summary
- Use TypeScript
for
Loop statements to execute a piece of code repeatedly.
while
The original address
In this tutorial, you’ll learn how to create loops using TypeScript’s while statement.
An introduction to TypeScript’s while statement
The while statement allows you to create a loop that executes the given code as long as the condition is true. Here is the syntax for a while statement in TypeScript:
while (condition) {
// do something
}
Copy the code
The while evaluates condition before each iteration of the loop:
- if
condition
The value oftrue
,while
The statement executes the code in its loop body; - if
condition
The calculated result isfalse
Break out of the loop and executewhile
The statement following the loop statement.
Since the while statement evaluates the condition before executing the body of the loop, it is also called a prediction loop.
We can use if and break statements to break the loop if certain conditions are true:
while (condition) {
// do something
// ...
if (anotherCondition) break;
}
Copy the code
If you want to execute a loop a certain number of times, you can use the for loop statement in TypeScript.
While statement example
Let’s look at a few examples of TypeScript while statements.
A simple while statement example
The following example uses a while statement to determine when counter is less than 5 and print its value to the console:
let counter = 0;
while (counter < 5) {
console.log(counter);
counter++;
}
Copy the code
Output:
0, 1, 2, 3, 4Copy the code
Here’s how it works:
- First of all, the declaration
counter
Variable and initialize its value to0
; - Then, check before entering the loop
counter
Is the value of5
If so, outputcounter
And increment its value by one; - Finally, when
counter
Less than5
“, repeat the above steps.
While statement project practice
Suppose an HTML document has a list of the following elements:
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
Copy the code
The following example shows how to remove all
-
element using a while statement:
let list = document.querySelector('#list');
while (list.firstChild) {
list.removeChild(list.firstChild);
}
Copy the code
Here’s how it works:
- First of all, through
id
Variables andquerySelector()
Method find out<ul>
Elements; - Next, check
list
Elements of thefirstChild
Whether the first child exists, and if so, remove it. When the first child is deleted, the next child is automatically promoted to the first child. So, use thiswhile
Loop statements can be deletedlist
All child nodes on the element.
summary
- Use TypeScript
while
Statement to create an object as long as the condition istrue
Will always execute the loop.
do while
The original address
In this tutorial, you’ll learn how to use TypeScript’s do while statement to create a loop that stops only when the condition is false.
An introduction to TypeScript’s do while statement
Here is the syntax for the do while statement:
do {
// do something
} while (condition);
Copy the code
The do while statement executes the code in the body of the loop until condition evaluates to false. A do while statement executes its loop body at least once. Unlike a WHILE statement, a DO while statement does not evaluate the condition until the end of each iteration of the loop, so it is also called a post-test loop.
Examples of TypeScript do while statements
The following example uses the do while statement to print numbers between 0 and 9 to the console:
let i = 0;
do {
console.log(i);
i++;
} while (i < 10);
Copy the code
Output:
0
1
2
3
4
5
6
7
8
9
Copy the code
Here’s how it works:
- First, declare variables
i
To initialize the value of the loop before entering it0
; - Next, let’s put
i
Output to the console and increment by one. Then check if its value is less than10
If so, continue the loop untili
Is greater than or equal to10
.
break
The original address
In this tutorial, you’ll learn about the break statement in TypeScript, which can be used to break loops and switch statements.
Use the break statement to terminate the loop
The break statement allows you to terminate a loop, passing control of the program to the statements that follow the loop. You can use the break statement in for, while, and do while statements. The following example shows how to use the break statement in a for loop:
let products = [
{ name: 'phone'.price: 700 },
{ name: 'tablet'.price: 900 },
{ name: 'laptop'.price: 1200},];for (var i = 0; i < products.length; i++) {
if (products[i].price == 900) break;
}
// show the products
console.log(products[i]);
Copy the code
Output:
{ name: 'tablet', price: 900 }
Copy the code
Here’s how it works:
- First initialize one with name and price attributes
products
Variable list; - Then, find the price is
900
When the product is found, use itbreak
Statement breaks loop; - Finally, we output the products that meet the requirements to the console.
Interrupts the switch statement with the break statement
The following example returns the discount for the specified product and interrupts the switch statement with the break statement:
let products = [
{ name: 'phone'.price: 700 },
{ name: 'tablet'.price: 900 },
{ name: 'laptop'.price: 1200},];let discount = 0;
let product = products[1];
switch (product.name) {
case 'phone':
discount = 5;
break;
case 'tablet':
discount = 10;
break;
case 'laptop':
discount = 15;
break;
}
console.log(`There is a ${discount}% on ${product.name}. `);
Copy the code
Note that in addition to loop statements and switch statements, the break statement can also be used to interrupt labeled statements, but it is rarely used in practice and will not be discussed further in this tutorial.
continue
The original address
In this tutorial, you’ll learn about the continue statement in TypeScript.
The continue statement is used for auxiliary control loops, such as for loops, while loops, or do while loops. The continue statement skips to the end of the current loop and begins the next loop iteration.
Use the continue statement in the for loop
The following example demonstrates how to use the continue statement in a for loop:
for (let index = 0; index < 9; index++) {
// if index is odd, skip it
if (index % 2) continue;
// the following code will be skipped for odd numbers
console.log(index);
}
Copy the code
Output:
0, 2, 4, 6, 8Copy the code
In this example:
- First, loop
0
到9
These numbers; - Then, when the number is odd, use
continue
The statement skips printing a number to the console and prints it to the console when the number is even.
Use the continue statement in the while loop
The following example shows how to use a continue statement in a while loop, which returns the same result as the above example:
let index = -1;
while (index < 9) {
index = index + 1;
if (index % 2) continue;
console.log(index);
}
Copy the code
Output:
0, 2, 4, 6, 8Copy the code
Use the continue statement in the do while loop
The following example shows how to use the continue statement in a do while loop, which returns the number of even numbers that exist between 9 and 99:
let index = 9;
let count = 0;
do {
index += 1;
if (index % 2) continue;
count += 1;
} while (index < 99);
console.log(count); / / 45
Copy the code