Vi. statements
6.1 If statement
One of the most commonly used statements in most programming languages is the IF statement. The following is the syntax for the IF statement:
if (condition) statement1 else statement2
The condition (condition) can be an arbitrary expression, and the result of evaluating the expression is not necessarily a Boolean value. ECMAScript automatically calls the Boolean () conversion function to convert the result of this expression to a Boolean value. If the result of condition evaluation is true, then statement1 (statement 1) is executed and Statement2 (statement 2) is executed if the result of condition evaluation is false. And these two statements can be either a single line of code or a block of code (multiple lines of code enclosed in a pair of curly braces).
Take a look at the example below.
if (i > 25)
Alert ("Greater than 25."); Single-line statement
else {
Alert ("Less than or equal to 25."); Statements in a code block
}
Alternatively, you can write the entire if statement in one line of code as follows:
if (condition1) statement1 else if (condition2) Statement2 else Statement3
if (i > 25) {
Alert ("Greater than 25.");
} else if (I < 0) {
Alert ("less than 0.");
} else {
Alert ("Between 0 and inclusive.");
}
6.2 Do-while Statements
The Do-while statement is a post-test looping statement that tests export conditions only after the code in the loop body executes.
In other words, the code in the loop body is executed at least once before the conditional expression is evaluated. The following is the syntax for the Do-while statement:
do {
Statement
} while (expression);
Here is an example:
var i = 0;
do {
i + = 2;
} while (I < 10);
alert (i);
In this case, as long as the value of the variable i is less than 10, the loop will go on. And the value of the variable i is initially 0, and each loop increments by 2.
6.3 While statement
The while statement belongs to the pre-test loop statement, which means that the exit condition is evaluated before the code in the loop body is executed.
Therefore, the code in the loop body may never be executed. The following is the syntax for the while statement:
while (expression) statement
Here is an example:
var i = 0;
while (I < 10) {
i + = 2;
}
In this example, the variable I starts with a value of 0 and increments by 2 for Each loop. And as long as the value of I is less than 10, the loop will go on.
6.4 For statement
The For statement is also a pre-test loop statement, but it has the ability to initialize variables and define the code to execute after the loop before executing the loop. The following is the syntax for the FOR statement:
for (initialization; expression; post-loop-expression) statement
Here is an example:
var count = 10;
for (var i = 0; i < count; i++) {
alert (i);
}
The above code defines the initial value of the variable i as 0. The For loop is entered only if the conditional expression (I<count) returns True, so it is also possible that the code in the loop body will not be executed. If the code in the loop body is executed, it is bound to evaluate the post-loop expression (i++), which is the value of increment i. This for Loop statement has the same functionality as the following while statement:
var count = 10;
var i = 0;
while (I < count) {
alert (i);
i++;
}
The use of a For loop does not work with a while loop. In other words, the For loop simply concentrates the loop-related code in one place.
It is important to note that the VAR keyword can also be used in a for-loop variable initialization expression. The initialization of the variable can be performed externally, for example:
var count = 10;
var i;
for (i = 0; i < count; i++) {
alert (i);
}
Because there is no block-level scope in ECMAScript, variables defined inside the loop can also be accessed externally. For example:
var count = 10;
for (var i = 0; i < count; i++) {
alert (i);
}
alert (i); 10
Even though I is a variable defined inside the loop, it can still be accessed outside the loop.
In addition, initialization expressions, control expressions, and post-loop expressions in a For statement are optional. Omitting all three expressions will create an infinite loop, for example:
for (;;) {//Infinite loop
DoSomething ();
}
Instead, only the control expression is actually converting the For loop into a while loop, for example:
var count = 10;
var i = 0;
for (; i < count;) {
alert (i);
i++;
}
6.5 for-in Statements
The for-in statement is a precise iterative statement that can be used to enumerate the properties of an object. The following is the syntax for the for-in statement:
For (property in expression) statement
Here is an example:
for (var propname in window) {
document.write (propname);
}
In this example, we use the for-in loop to display all the properties of the Window object in the BOM. Each time a loop is executed, a property name that exists in the Window object is assigned to the variable propname. This process persists until all properties in the object are enumerated again. Similar to the For statement, the VAR operator in the control statement is not required. However, to ensure the use of local variables, we recommend this approach in the example above.
The properties of the ECMAScript object are not in order. Therefore, the order of the property names that are output through the for-in loop is unpredictable. In particular, all properties are returned once, but the order in which they are returned may vary by browser.
However, if the variable value that represents the object being iterated is null or the Undefined,for-in statement throws an error. ECMAScript 5 corrects this behavior, and no more errors are thrown in this case, but the loop body is not executed. For maximum compatibility, it is recommended to detect that the value of the object is not null or undefined before using the for-in loop.
6.6 Label Statement
Use the Label statement to add tags to your code for future use. The following is the syntax for a label statement:
Label:statement
Here is an example:
Start:for (var i=0; i < count; i++) {
alert (i);
}
The start tag defined in this example can be referenced in the future by a break or a continue statement. Tagged statements are generally used in conjunction with loop statements such as for statements.
6.7 Break and Continue statements
The break and continue statements are used to precisely control the execution of code in a loop. Where the break statement exits the loop immediately, forcing the statement following the loop to continue execution. The continue statement, though, exits the loop immediately, but exits the loop and resumes from the top of the loop. Take a look at the following example:
var num = 0;
for (var i=1; i <; i++) {
if (i% 5 = = 0) {
Break
}
num++;
}
alert (num); 4
After the break statement is executed, the next line of code to execute is the alert () function, and the result is 4. That is, the loop executes 4 times at the variable I equals 5 o'clock, and the execution of the break statement causes the loop to exit before Num increments again. If you replace break with continue here, you can see another result:
var num = 0;
for (var i=1; i <; i++) {
if (i% 5 = = 0) {
Continue
}
num++;
}
alert (num); 8
The results of the example show 8, that is, the loop was executed 8 times in total. When the variable i equals 5 o'clock, the loop exits before Num increments again, but the next loop is executed, that is, the value of I equals 6 of the loop. As a result, the loop continues to execute until I equals 10 o'clock natural end. The final value of NUM is 8 because the continue statement causes it to increment a little.
Both the break and continue statements can be used in conjunction with a label statement to return a specific location in the code. This combination of usage occurs in the case of loop nesting, as shown in the following example:
var num = 0;
Outermost:
for (var i=0; i <; i++) {
for (var j=0; J <; J + +) {
if (i = = 5 && J = = 5) {
Break outermost;
}
num++;
}
}
alert (num); 55
The outermost label represents the external for statement. If each loop executes 10 times normally, the num++ statement executes 100 times. In other words, if two loops end naturally, the value of NUM should be 100. But the break statement in the inner loop takes a parameter: the label to return to. The result of adding this tag will cause the break statement not only to exit the internal for statement (that is, to use the variable J loop), but also to exit the external for statement (that is, the loop using the variable i). For this reason, when the variables I and J are equal to 5 o'clock, the value of num is exactly 55.
The continue statement can also be associated with a label statement like this, for example:
var num = 0;
Outermost:
for (var i=0; i <; i++) {
for (var j=0; J <; J + +) {
if (i = = 5 && J = = 5) {
Continue outermost;
}
num++;
}
}
alert (num); 95
In this case, the continue statement forces the continuation of the loop--exiting the inner loop and executing the outer loop. When J is 5 o'clock, the Continue statement executes, which means that the internal loop is executed less than 5 times, so NUM has a result of 95.
6.8 with statements
The function of the WITH statement is to set the scope of the code to a specific object. The syntax for the WITH statement is as follows:
With (expression) statement;
The purpose of defining the with statement is primarily to simplify the work of writing the same object multiple times, as shown in the following example:
var qs = location.search.substring (1);
var hostName = Location.hostname;
var url = location.href;
The previous lines of code contain the Location object. If you use the WITH statement, you can rewrite the above code as follows:
With (location) {
var qs = search.substring (1);
var hostName = HostName;
var url = href;
}
In this rewritten example, the location object is associated with a with statement. This means that within the code block of the WITH statement, each variable is first considered a local variable, and if the definition of the variable is not found in the local environment, the location object is queried for properties with the same name. If a property of the same name is found, the value of the Location object property is used as the value of the variable.
The WITH statement is not allowed in strict mode, otherwise it is considered a syntax error.
The use of with statements is not recommended when developing large applications because of the performance degradation caused by the large use of with statements and the difficulty of debugging code.
6.9 switch statement
The switch statement is most closely related to the IF statement and is also a flow control statement commonly used in other languages.
The syntax of the switch statement in ECMAScript is very similar to other C-based languages, as follows:
switch (expression) {
Case Value:statement
Break
Case Value:statement
Break
Case Value:statement
Break
Case Value:statement
Break
Default:statement
}
The meaning of each case in the switch statement is: "If the expression equals this value (value), then the following statement (statement) is executed." The break keyword causes the code execution flow to jump out of the switch statement. If you omit the break keyword, it causes the next case to continue after the current case is executed. The last default keyword is used when the expression does not match any of the preceding cases, and the maneuver code is executed (and therefore, the equivalent of an else statement).
Fundamentally, the switch statement is designed to keep developers from writing code like this:
if (i = = 25) {
Alert ("25");
} else if (i = = 35) {
Alert ("35");
} else if (i = = 45) {
Alert ("45");
} else {
Alert ("other");
}
and the equivalent switch statement is as follows:
switch (i) {
Case 25:
Alert ("25");
Break
Case 35:
Alert ("35");
Break
Case 45:
Alert ("45");
Break
Default
Alert ("other");
}
By adding a break statement after each case, you can avoid situations where multiple cases code is executed at the same time. If you do need to mix several scenarios, don't forget to add a comment to the code stating that you intentionally omitted the break keyword as follows:
switch (i) {
Case 25:
Case 35:/* Merge two scenarios */
Alert ("or 35");
Break
Case 45:
Alert ("45");
Break
Default
Alert ("other");
}
This statement also has its own characteristics, first, you can use any data type in the switch statement (only numeric values are used in many other languages), whether it is a string or an object. Second, the value of each case is not necessarily a constant, it can be a variable, or even an expression. Take a look at the following example:
switch ("Hello World") {
Case ' Hello ' + ' world ':
Alert ("Greeting was found.");
Break
Case "Goodbye":
Alert ("Closing was found.");
Break
Default
Alert ("unexpected message was found.");
}
The first scenario is actually an expression that evaluates a string concatenation operation. Since the result of this string concatenation expression is equal to the parameter of switch, the result is "greeting was found." Also, using an expression as a case value enables the following actions:
var num = 25;
Switch (TRUE) {
Case Num < 0:
Alert ("less than 0.");
Break
Case num >= 0 && num <= 10:
Alert ("Between 0 and 10.");
Break
Case num > && num <= 20:
Alert ("Between and 20.");
Break
Default
Alert ("More than 20.");
}
This example first declares the variable num outside the switch statement. The reason to pass an expression to the switch statement is true because each case value can return a Boolean value.
The switch statement uses the congruent operator when comparing values, so no type conversions occur (for example, the string "10" is not equal to the number 10).
Seven, function
Functions can encapsulate any number of statements, and can be invoked anywhere, at any time, to execute. Functions in ECMAScript are declared by using the function keyword followed by a set of parameters and the body of the function. The basic syntax for a function is as follows:
function functionname (arg0, arg1,..., ArgN) {
Statements
}
The following is an example of a function:
function Sayhi (name, message) {
Alert ("Hello" + name + "," + message);
}
This function can be called by its function name, followed by a pair of parentheses and arguments (if there are more than one parameter in the parentheses, it can be separated by commas). The code for calling the Sayhi () function is as follows:
Sayhi ("Nicholas", "How is you today?");
The output of this function is "Hello nicholas,how is you today?". The named parameter in the definition in the function name and message are used as the two operands of the string concatenation, and the result is finally shown by the warning box.
A function in ECMAScript does not have to specify whether to return a value when it is defined. In fact, any function can implement the return value at any time by the return statement followed by the value to be returned. Take a look at the following example:
function sum (NUM1, num2) {
return NUM1 + num2;
}
The function of the sum () function is to add up to two values to return a result. We notice that, in addition to the return statement, there is no declaration that the function returns a value. The example code that calls this function is as follows:
var result = SUM (5, 10);
This function stops and exits immediately after executing the return statement. Therefore, any code that is behind the return statement will never be executed. For example:
function sum (NUM1, num2) {
return NUM1 + num2;
Alert ("Hello World"); Will never execute
}
Because the statement that calls the alert () function is behind a return statement, the warning box is never displayed.
Of course, a function can also contain multiple return statements, as shown in the following example:
function diff (NUM1, num2) {
if (Num1 < num2) {
return NUM2-NUM1;
} else {
return num1-num2;
}
}
The diff () function defined in this example is used to calculate the difference of two values. If the first number is smaller than the second one, use the second number
Subtract the first number; otherwise, subtract the second number by the first number. Each of the two branches in the code has its own return statement, which is used to
Perform the correct calculation.
In addition, the return statement can have no return value. In this case, the function will return undefined after it has stopped executing
Value. This usage is generally used in cases where the function execution needs to be stopped prematurely without the return value. In the example below, for example,
No warning box is displayed:
function Sayhi (name, message) {
Return
Alert ("Hello" + name + "," + message); Will never call
}
Strict mode has some limitations on functions:
? The function cannot be named eval or arguments;
? The parameter cannot be named eval or arguments;
? Two named arguments cannot appear with the same name.
If this occurs, a syntax error is caused and the code cannot be executed.
7.1 Understanding Parameters
The ECMAScript function does not mind passing in the number of arguments, and does not care about what data type to pass in the parameter. In other words, even if you define a function that only receives two parameters, it is not necessarily necessary to pass two arguments when calling this function. You can pass one, three, or even pass parameters, and the parser will never complain. The reason for this is that the parameters in ECMAScript are internally represented by an array. The function always receives this array, regardless of which parameters are included in the array (if any). If the array contains no elements, it doesn't matter if you have more than one element. In fact, the parameter array can be accessed through the arguments object in the body of the function to obtain each parameter passed to the function.
In fact, the arguments object is just like an array (it is not an instance of an array), because each element of it can be accessed using square brackets syntax (i.e. the first element is rguments[0], the second element is argumetns[1], and so on), using the length property to determine how many parameters are passed in. In the previous example, the first parameter of the Sayhi () function is named name, and the value of the parameter can be obtained by accessing Arguments[0]. Therefore, the function can also be overridden as follows, that is, the named parameter is not explicitly used:
function Sayhi () {
Alert ("Hello" + arguments[0] + "," + arguments[1]);
}
This rewritten function does not contain named arguments. Although the name and message identifiers are not used, the function is still functional. This fact illustrates an important feature of the ECMAScript function: named parameters are only convenient, but not required. In addition, in terms of named parameters, other languages may need to create a function signature beforehand, and future calls must be consistent with that signature. But in ECMAScript, without these rules, the parser does not validate named parameters.
By accessing the length property of a arguments object, you can tell how many arguments are passed to the function. The following function will
The number of arguments that the output passes in each time it is called:
function Howmanyargs () {
alert (arguments.length);
}
Howmanyargs ("string", 45); 2
Howmanyargs (); 0
Howmanyargs (12); 1
Developers can take advantage of this to allow a function to receive arbitrary parameters and to implement the appropriate functionality separately. Take a look at the following example:
function Doadd () {
if (arguments.length = = 1) {
Alert (Arguments[0] + 10);
} else if (arguments.length = = 2) {
Alert (Arguments[0] + arguments[1]);
}
}
Doadd (10); 20
Doadd (30, 20); 50
Another important aspect related to parameters is that the arguments object can be used with named parameters, as shown in the following example:
function Doadd (NUM1, num2) {
if (arguments.length = = 1) {
Alert (NUM1 + 10);
} else if (arguments.length = = 2) {
Alert (Arguments[0] + num2);
}
}
There's something more interesting about arguments's behavior. That is, its value is always kept in sync with the value of the corresponding named parameter. For example:
function Doadd (NUM1, num2) {
ARGUMENTS[1] = 10;
Alert (Arguments[0] + num2);
}
Doadd (5,2);//15
Doadd (5);//nan
Each execution of the Doadd () function overrides the second parameter, modifying the value of the second parameter to 10. Because the values in the arguments object are automatically reflected in the corresponding named arguments, modifying the arguments[1] also modifies the num2, resulting in their values becoming 10. However, this is not to say that reading these two values accesses the same memory space; their memory space is independent, but their values are synchronized. Also keep in mind that if only one parameter is passed in, the value set for ARGUMENTS[1] will not be reflected in the named parameter. This is because the length of the arguments object is determined by the number of arguments passed in, not by the number of named arguments when the function is defined.
The last thing to remember about parameters is that named parameters that do not pass values are automatically assigned the undefined value. This is the same as defining a variable without initializing it. For example, if you pass only one argument to the Doadd () function, the undefined value is saved in num2.
Strict mode makes some restrictions on how to use arguments objects. First, assignments like those in the previous example become invalid. That is, even if you set arguments[1] to 10,num2, the value is still undefined. Second, overriding the value of arguments results in a syntax error (the code will not execute).
All parameters in the ECMAScript are passed as values, and arguments cannot be passed by reference.
7.2 No Overloads
The ECMAScript function does not implement overloading as it is in the traditional sense. In other languages, such as Java, you can write two definitions for a function, as long as the two defined signatures (the type and number of parameters that are accepted) are different. As mentioned earlier, the ECMASCIRPT function has no signature because its arguments are represented by an array containing 0 or more values. Without a function signature, the real overload is impossible.
If two functions with the same name are defined in ECMAScript, the name belongs only to the post-defined function, because the function defined later overrides the function that was defined first. Take a look at the following example:
function Addsomenumber (num) {
return num + 100;
}
function Addsomenumber (num) {
return num + 200;
}
var result = Addsomenumber (100); 300
As mentioned earlier, you can mimic the overloads of a method by examining the type and number of parameters in the incoming function and reacting differently.
Chapter III Basic Concepts (bottom)-JavaScript advanced Programming