6
头图
"Code tailor" provides technical-related information and a series of basic articles for front-end developers. Follow the "Novices of Xiaoheshan" public account on WeChat to get the latest articles in time.

Preface

Before starting to learn, what we want to tell you is that this article is a JavaScript "process control" in 060a326b2e7cd2 language knowledge. If you have mastered the following knowledge items, you can skip this section and go directly to the topic exercise

  • if statement
  • while, do-while statements
  • for statement, for-in statement, for-of statement
  • break statement and continue statement
  • switch statement
  • try/catch statement

Summary

ECMA-262 describes some sentences (also called flow control sentences), and ECMAScript is reflected in the sentences. Statements usually use one or more keywords to complete a given task. The statement can be simple or complex. Simple as telling the function to exit, complicated as listing a bunch of instructions to be executed repeatedly.

if statement

if statement is one of the most frequently used statements, the syntax is as follows:

if (condition) {
  statement1
} else {
  statement2
}

The condition ( condition ) here can be any expression, and the evaluation result is not necessarily a Boolean value. ECMAScript will automatically call the Boolean() function to convert the value of this expression to a Boolean value. If the condition evaluates to true , the statement statement1 is executed; if the condition evaluates to false , the statement statement2 is executed. The statement here may be a line of code, or it may be a code block (that is, multiple lines of code enclosed in a pair of curly braces) such as the following code:

if (xhs > 1) {
  console.log('xhs满足大于1!')
} else {
  console.log('xhs不满足大于1!')
}

In the above code, when xhs meets greater than 1 , the output xhs meets greater than 1! , When xhs does not satisfy greater than 1 , the output xhs does not satisfy greater than 1! .

You can use multiple if statements in succession like this:

if (condition1) {
  statement1
} else if (condition2) {
  statement2
} else {
  statement3
}

Below is an example:

if (xhs > 25) {
  console.log('xhs满足大于25')
} else if (xhs < 0) {
  console.log('xhs满足小于0')
} else {
  console.log('xhs在0到25之间')
}

do-while statement

do-while statement is a post-test loop statement, that is, the exit condition will not be evaluated until the code in the loop body is executed. In other words, loop is executed at least once . do-while is as follows:

do {
  statement
} while (expression)

Below is an example:

let xhs = 0
do {
  xhs += 2
} while (xhs < 10)

In the above example, the variable xhs first adds 2 , and then uses 2 to 10 , if it is less than 10 , the loop will repeat until xhs >= 10 .

Note that the often used in this situation: the code in the loop must be executed at least once before exiting.

while statement

while statement is a loop statement first, that is, the exit condition is detected first, and then the code in the loop body is executed. Therefore, while loop may not be executed. The following is the syntax while

while (expression) {
  statement
}

This is an example:

let i = 0
while (i < 10) {
  i += 2
}

In this example, the variable xhs starts from 0 2 each time it loops. As long as xhs less than 10 , the cycle will continue.

for statement

for statement is also the first test statement, except that the initialization code before entering the loop ( initialization ) and the expression to be executed after the loop is executed ( loop-expression ) are added. The syntax is as follows:

for (initialization; expression; loop - expression) {
  statement
}

Here is a use case:

let xhsLength = 10
for (let xhs = 0; xhs < xhsLength; xhs++) {
  console.log(xhs)
}

The above code defines the initial value of xhs 0 . Then evaluate the conditional expression. If the evaluation result is true (xhs < xhsLength) , the loop body is executed. Therefore, the loop body may not be executed. If the body of the loop is executed, the expression will be executed after the loop to increment the variable xhs . for cycle with the following while cycle is the same:

let xhsLength = 10
let xhs = 0
while (xhs < xhsLength) {
  console.log(xhs)
  xhs++
}

Logic that cannot be realized by the while for loop. Therefore, the for loop just encapsulates the loop-related code together.

In for loop, in fact, it is not necessary to use the variable declaration keyword. However, it is almost impossible to use the iterator variables defined by the initialization after the loop is executed. Therefore, the clearest way to write is to use let declare the iterator variable, so that the scope of this variable can be limited to the loop.

Initialization, conditional expressions, and post-loop expressions are not required. Therefore, the following writing can create an infinite loop:

for (;;) {
  // 无穷循环
  doSomething()
}

If only the conditional expression is included, then the for loop actually becomes the while loop:

let xhsLength = 10
let xhs = 0
for (; xhs < xhsLength; ) {
  console.log(xhs)
  xhs++
}

This versatility makes for sentences very widely used in this language.

for-in statement

for-in statement is a strict iterative statement that is used to enumerate non-symbolic key attributes in an object. The syntax is as follows:

for (property in expression) {
  statement
}

Below is an example:

for (const xhsName in object) {
  console.log(xhsName)
}

This example uses for-in cycle through all the attributes of the object object Each time the loop is executed, the variable xhsName will be assigned an object object as the value, until object have been enumerated again. Like the for const in the control statement here is not necessary. But in order to ensure that this local variable is not modified, it is recommended to use const .

ECMAScript of the objects in 060a326b2e82ce are out of order, so the for-in statement cannot guarantee the order in which the attributes of the objects are returned. In other words, all enumerable properties are returned once, but the order of return may vary from browser to browser.

If the variable to be iterated by the for-in null or undefined , the loop body is not executed.

for-of statement

for-of statement is a strict iterative statement used to traverse iterable object . The syntax is as follows:

In other words, as long as the prototype object implements the @@iterator method, the object can be for-of
for (property of expression) {
  statement
}

Here is an example:

for (const xhsName of [2, 4, 6, 8]) {
  console.log(xhsName) //分别打印2,4,6,8
}

In this example, we use the for-of display all the elements in an array containing 4 elements. The loop will continue until all elements are iterated. Like the for const in the control statement here is not necessary. But in order to ensure that this local variable is not modified, it is recommended to use const .

for-of loop will iterate the elements in the order in which the next() For details about iterable objects, please refer to the Iterator of the ES6 series.

If the variable you are trying to iterate does not support iteration, the for-of statement will throw an error.

break and continue statements

break and continue statements provide a more stringent control method for executing loop code. Among them, the break statement is used to immediately exit the loop and force the execution of the next statement after the loop. The continue statement is also used to exit the loop immediately, but it will execute again from the top of the loop. Let's look at an example:

for (let xhs = 1; xhs < 10; xhs++) {
  if (xhs % 5 == 0) {
    break
  }
  xhsNumber++
}
console.log(xhsNumber) // 4

In the above code, the for loop will increment the xhs from 1 10 . In the loop body, there is a if statement to check xhs can be divisible (using the modulo operator). If it is, execute the break statement to exit the loop. The initial value of the variable xhsNumber 0 , which indicates how many times the loop is executed before exiting. When the break is executed, the code executed in the next line is console.log(num) , which displays 4 . The reason why the loop is executed 4 times is because when xhs is equal to 5 , the break statement will cause the loop to exit. This loop will not execute the code xhsNumber If you change break to continue , different effects will appear:

let xhsNumber = 0
for (let xhs = 1; xhs < 10; xhs++) {
  if (xhs % 5 == 0) {
    continue
  }
  xhsNumber++
}
console.log(xhsNumber) // 8

This time, console.log shows 8 , which means that the loop has been executed 8 times. When xhs is equal to 5 , the loop will xhsNumber , but the next iteration will be executed. At this time, xhs is 6 . Then, the loop will be executed until the natural end, that is, xhs is equal to 10 . The final xhsNumber value is 8 instead 9 , because continue statement causes it less incremented once.

break and continue can be used with label statements to return a specific position in the code. This is usually in a nested loop, as shown in the following example:

let xhsNumber = 0
xhsRookies: for (let xhs = 0; xhs < 10; xhs++) {
  for (let xhsJJ = 0; xhsJJ < 10; xhsJJ++) {
    if (xhs == 5 && xhsJJ == 5) {
      break xhsRookies
    }
    xhsNumber++
  }
}
console.log(xhsNumber) // 55

In this example, the xhsRookies tag identifies the first for statement. Under normal circumstances, each loop is executed 10 times, which means xhsNumber++ statement will execute 100 times, but at the end of the cycle console.log results should be 100 . However, the break statement brings a variable, that is, the label to exit to. Adding tags not only makes break exit the inner loop, it also exits the outer loop. When performing the xhs and xhsJJ are equal 5 , the loop stops executing, at this time xhsNumber value is 55 . continue statement can also use labels, as shown in the following example:

let xhsNumber = 0
xhsRookies: for (let xhs = 0; xhs < 10; xhs++) {
  for (let xhsJJ = 0; xhsJJ < 10; xhsJJ++) {
    if (xhs == 5 && xhsJJ == 5) {
      continue xhsRookies
    }
    xhsNumber++
  }
}
console.log(xhsNumber) // 95

This time, the continue statement will force the loop to continue execution, but instead of continuing to execute the inner loop, it continues to execute the outer loop. When xhs and xhsJJ are equal 5 time, performs continue , skip external circulation continues, resulting in the implementation of at least five times the inner loop, the result xhsNumber equal 95 .

Combining label statements with break and continue can realize complex logic, but it is also prone to errors. Note that the label should use descriptive text, and the nesting should not be too deep.

switch statement

switch statement is a flow control statement closely related to the if

switch (expression) {
  case value1:
    statement
    break
  case value2:
    statement
    break
  case value3:
    statement
    break
  case value4:
    statement
    break
  default:
    statement
}

Each case (condition/branch) here is equivalent to: "If the expression is equal to the following value, execute the following statement." The break keyword will cause the code execution to jump out of the switch statement. If there is no break , the code will continue to match the next condition. default keyword is used to specify the statement to be executed by default when no conditions are met (equivalent to the statement else ).

With the switch statement, developers don’t need to write code like this:

if (xhs == 25) {
  console.log('25')
} else if (xhs == 35) {
  console.log('35')
} else if (xhs == 45) {
  console.log('45')
} else {
  console.log('xhsRookies')
}

Instead, it can be written like this:

switch (xhs) {
  case 25:
    console.log('25')
    break
  case 35:
    console.log('35')
    break
  case 45:
    console.log('45')
    break
  default:
    console.log('xhsRookies')
}

In order to avoid unnecessary condition judgment, it is best to add break sentence after each condition. If you really need to match several conditions in a row, it is recommended to write a note to indicate that break is deliberately ignored, as shown below:

switch (xhs) {
  case 25:
    console.log('25')
  /*跳过*/
  case 35:
    console.log('25 or 35')
    break
  case 45:
    console.log('45')
    break
  default:
    console.log('xhsRookies')
}

ECMAScript gives switch some unique characteristics. First of all, the switch statement can be used for all data types (in many languages, it can only be used for numbers), so you can use strings and even objects. Second, the value of the condition does not need to be a constant, it can also be a variable or an expression. Look at the following example:

switch ('hello xhsRookies') {
  case 'hello' + ' xhsRookies':
    console.log('hello,xhs-rookies')
    break
  case 'goodbye':
    console.log('goodbye,xhs-rookies')
    break
  default:
    console.log('sorry,xhs-rookies')
}

This example uses character strings switch The first condition actually uses an expression, which evaluates to the result of the concatenation of two strings. Because the result of splicing equal switch parameters, so console.log outputs hello,xhs-rookies . If you can use expressions in conditional judgments, you can add more logic to the judgments:

let xhsNumber = 25
switch (true) {
  case xhsNumber < 0:
    console.log('xhsNumber less than 0.')
    break
  case xhsNumber >= 0 && xhsNumber <= 10:
    console.log('xhsNumber between 0 and 10.')
    break
  case xhsNumber > 10 && xhsNumber <= 20:
    console.log('xhsNumber between 10 and 20.')
    break
  default:
    console.log('xhsNumber more than 20.')
}

The above code first defines the variable xhsNumber externally, and the parameter passed to the switch true because the expression of each condition returns a boolean value. The expressions of the conditions are evaluated separately until an expression returns true . Otherwise, it will jump to the default statement (this example is exactly the case).

try/catch statement

try/catch statement, as JavaScript , the basic syntax is as follows:

try {
  // 可能出错的代码
} catch (error) {
  // 出错时要做什么
}

Any code that may be wrong should be placed in the try block, and the code for handling errors catch block, as shown below:

try {
    dosome...
} catch (error) {
    console.log("An error happened!");
}

If try block, the code will immediately exit the execution and jump to the catch block. catch receives an object at this time, which contains information about the error.

try/catch finally clause in the 060a326b2e8934 statement always runs. If the code in block try is finished, then the code in block finally If an error catch and the code in block finally is still executed. try or catch block cannot prevent the finally block from executing, including the return statement

try {
  return 2
} catch (error) {
  return 1
} finally {
  return 0
}

In this try/catch various parts of the statement only put a return statement. It seems that the function should return 2 , because it is in the try block and will not cause an error. However, finally there is a block of lead try block return statement is ignored. Therefore, calling try/catch under any circumstances will return 0 . If you remove the finally clause, the function will return 2 . If you write the finally clause, the catch block becomes optional.

Self-test questions

1. What does the following code output?

let xhsA = 1,
  xhsB = 0
while (xhsA <= 100) {
  xhsB = xhsB + xhsA
  xhsA++
}
console.log(xhsB)

let xhsC = 1,
  xhsD = 0
do {
  xhsD = xhsD + xhsC
  xhsA++
} while (xhsC <= 100)

console.log(xhsD)

let xhsE = 0
for (let xhsF = 1; xhsF <= 100; xhsF++) {
  xhsE += xhsF
}
console.log(xhsE)

2. What does the following code output?

let xhsType = 'teacher'
switch (xhsType) {
  case 'student':
    console.log('我是student!')
    break
  case 'teacher':
    console.log('我是teacher!')
  case 'parent':
    console.log('我是parent!或者 我是teacher')
    break
  default:
    console.log('我是person!')
}

3. What does the following code output?

try {
  let xhsNumber1 = 10
  console.log(xhsNumber1)
} catch (error) {
  let xhsNumber2 = 10 / 2
  console.log(xhsNumber2)
} finally {
  let xhsNumber3 = 10 / 5
  console.log(xhsNumber3)
}

Problem analysis

One,

Answer 5050 5050 5050

This question examines the while , do while , for loop statements, the first while loop defines xhsA=1 , and satisfies the 100 , so the loop executes the loop xshB = xhsB + xhsA;xhsA++; xshA not equal to 100 until 1+2+3+4+······+99+100=5050 . second do while cycles, and while cycle, as the only difference is that, do while cycling conditions, no matter what, the first pass through the code blocks, and then determines xhsC meets less 100 , the final output 5050; for cycle start defined xhsF=1 , If it is less than or equal to 100 , so loop xhsE+=xhsF; until xhsF not satisfied or less than 100 , exit the loop, this loop is also equivalent to 1+2+3+4+······+99+100=5050

two,

Answer I am a teacher! I am the parent! Or I am teacher

This question examines the switch loop statement. At the beginning, define xhsType = 'teacher'; pass in the switch statement, match case 'teacher': execute the following statement, and output "I am a teacher!". Because there is no break; statement to break out of the loop, the subsequent statement output "I am the parent! Or I am the teacher", break; jump out of the loop when I encounter 060a326b2e8c88

three,

Answer 10 2

This question examines the try/catch statement. In the try block, the value of 10 is defined as xhsNumber1 , and then printed out. No error is thrown in this process, so the catch block will not be executed, but finally will not be executed, regardless of the code in try there is no block error is thrown, will be executed, the output xhsNumber3 value 2 .


小和山的菜鸟们
377 声望2.1k 粉丝

每日进步的菜鸟,分享前端学习手册,和有心学习前端技术的小伙伴们互相探讨,一同成长。