Javascript Learning (1)-basic syntax

Source: Internet
Author: User
Tags javascript array

JavaScript is becoming more and more popular. It can be said that it is one of the most prominent languages on the Internet. You can use it across platforms and Browsers without rejecting backend languages. There are many different development libraries -- some of which are great -- these libraries are very helpful for development, such as speeding up development. The problem is that sometimes these libraries have some distance from the original language, which makes beginners lack a basic understanding of the language.

This article describes the basic principles of the language by comprehensively listing the basic JavaScript concepts, so as to provide beginners with a basic understanding of the language, code examples that are everywhere are used to demonstrate how all these concepts are embodied in the language.

Understanding JavaScript Language

JavaScript is a free client scripting Language that allows you to add interaction behavior to the Hypertext Markup Language (HTML) page. Client-side means that JavaScript runs in the browser, rather than on the server. After the webpage is delivered by the server and loaded by the browser, the client script allows users to interact with the webpage. For example, Google Maps uses JavaScript to support interaction between users and Maps. The interaction methods include moving Maps, enlarging and narrowing down. Without the JavaScript language, the webpage needs to refresh the interaction behavior with each user each time, unless the page uses Adobe Flash or Microsoft®Silverlight plug-ins. The JavaScript language does not require plug-ins.

Because the JavaScript language provides user interaction for the loaded webpage, developers usually use it to implement the following functions:

1. dynamically add, edit, and delete HTML elements and their values.

2. Verify the form before submission.

3. Create cookies on your computer to store and retrieve data for future access.

Before you start, you only need to know the basic principles of the language:

1. to include JavaScript code in an HTML file, you must put the code inside the script tag and add the text/javascript type (type) attribute (List 1 ).

2. All JavaScript statements end with a semicolon.

3. The language is case sensitive.

4. All variable names must start with letters or underscores.

5. You can use comments to describe certain rows in the script. The comments are written starting with a double slash (//) and followed by comments.

6. You can also use annotations to comment out the script. To comment out multiple lines of the script, a good way is to use/* your script here */. Any script within the asterisk will not run during execution.

Listing 1. The script tag and type attribute must be used to include JavaScript code in the HTML file.

<Script type = "text/javascript"> </script>
<Script type = "text/javascript"> </script>
To hide the JavaScript code not supported by the browser, or to disable the code, you only need to use the annotation label before and after the commit Crip Statement (List 2 ).

Listing 2. Using annotations to hide JavaScript code not supported by the browser

<Script type = "text/javascript">
<! -- Example statement here // -->
</Script>
<Script type = "text/javascript">
<! -- Example statement here // -->
</Script>

The most common method to include JavaScript code into a webpage is to use the src attribute in the script tag to load the code from an external JavaScript file (listing 3 ).

Listing 3. Adding external JavaScript files to an HTML file

<Script type = "text/javascript" src = "path/to/javascript. js" kesrc = "path/to/javascript. js"> </script>
<Script type = "text/javascript" src = "path/to/javascript. js" kesrc = "path/to/javascript. js"> </script>
 
External JavaScript files are the most common way to include JavaScript code. There are some very real reasons:

1. If your HTML page contains less code, the search engine can crawl and index your website at a faster speed.

2. Keep JavaScript code and HTML separated so that the code is clearer and easier to manage.

3. because you can include multiple JavaScript files in HTML code, you can separate JavaScript files and place them in different file directory structures on the web server. This is similar to storing images, this is an easier way to manage code. Clear and organized code is always the key to making website management easier.

Variable

Variable storage data, which will be retrieved later or updated using new data. The data stored in the variable can be a value or expression. The JavaScript language has three types of expressions, which are described in table 1.

Table 1. JavaScript expressions

Expression description

The result of arithmetic calculation is a numerical value.

Returns a string.

The result of logical calculation is a Boolean value (true or false)

There are two types of variables: local and global. Local variables are declared using the var keyword. If you declare a global variable, you do not need to use the var keyword. Variables that use the var keyword are considered local, because they cannot be accessed anywhere except where you declare them. For example, if you declare a local variable in a function (which I will talk about at the end of this Article), the variable cannot be accessed outside the function, this makes it part of this function. If you do not use the var keyword to declare the same variable, it will be accessible throughout the script, not only limited to being accessed in that function.

Listing 4 provides an example of a local variable named num and assigned 10 values.

Listing 4. Declaring a local variable

Var num = 10;
Var num = 10;
To access the value of the num variable at another location in the script, you only need to reference the variable by name, as shown in listing 5.

Listing 5. Access variable values

Document. write ("The value of num is:" + num );
Document. write ("The value of num is:" + num );
The result of this statement is "The value of num is: 10 ". This document. write function writes data to the web page. In the rest of this article, you use this function to write the example to the web page.

To store an arithmetic expression in a variable, you only need to assign the variable to the calculated value, as shown in Listing 6. The calculation result is stored in the variable instead of the formula itself. Therefore, we obtain The result "The value of num is: 10" again ".

Listing 6. Store arithmetic expressions


Var num = (5 + 5 );
Document. write ("The value of num is:" + num );
Var num = (5 + 5 );
Document. write ("The value of num is:" + num );
To change the value of a variable, reference the variable by the name you assign to the variable, and assign a new value to it by using the equal sign (listing 7 ). The difference this time is that you do not need to use the var keyword because the variable has been declared.

Listing 7. Changing the value of an existing variable


Var num = 10;
Document. write ("The value of num is:" + num); // update The value of num to 15 num = 15;
Document. write ("The new value of num is:" + num );
Var num = 10;
Document. write ("The value of num is:" + num); // update The value of num to 15 num = 15;
Document. write ("The new value of num is:" + num );

The result of this script is "The value of num is: 10", followed by "The new value of num is: 15 ". In addition to variables, this section also introduces the next topic, that is, operators. The equal sign (=) that you assign a value to a variable is a value assignment operator, and the plus sign (+) that you use in 5 + 5 is an arithmetic operator. The next section describes all variable operators in JavaScript and their usage.

Operator

You need operators when executing any operations in JavaScript. Operations include addition, subtraction, and comparison. There are four operators in JavaScript.

1. Arithmetic

2. Assignment

3. Comparison

4. Logic

Arithmetic Operators

Arithmetic Operators perform basic mathematical operations, such as addition, subtraction, multiplication, division, and so on. Table 2 lists and describes all available arithmetic operations in the JavaScript language.

Table 2. Arithmetic Operators

Operator description

+ Addition

-Subtraction

* Multiplication

/Division

% Modulo (finding the remainder)

++ Increment

-- Decrease

Value assignment operator

Arithmetic Operators perform basic mathematical operations, while the value assignment operator assigns values to JavaScript variables. When you assign a value to a variable in the previous section, you have seen the most commonly used value assignment operator. Table 3 lists and describes all available value assignment operators in JavaScript.

Table 3. assignment operators

Operator description

= Equal

+ = Assign the addition value (the result value of the value added to the variable) to the variable

-= Assign the subtraction value (the result value of the variable minus the value) to the variable

* = Assign the multiplication value (the result value of the variable multiplication value) to the variable

/= Assign the Division value (the result value of the variable divided by the value) to the variable

% = Assign the modulo value (result of Modulo of the variable pair value) to the variable

You have seen how to use equal signs to assign values or expressions to variables, but now I will show you how to use a slightly confusing value assignment operator. Assigning an addition value to a variable may be a strange concept, but it is actually very simple (listing 8 ).

Listing 8. Assigning an addition value to a variable


Var num = 10;
Document. write ("The value of num is:" + num); // update The value of num to 15 num + = 5;
Document. write ("The new value of num is:" + num );
Var num = 10;
Document. write ("The value of num is:" + num); // update The value of num to 15 num + = 5;
Document. write ("The new value of num is:" + num );

The result of this script is "The value of num is: 10" followed by "" The new value of num is: 15 ". As you can see, the operator in this script assigns the addition value to the variable. This can also be considered as a short writing of the script written in listing 9.

Listing 9. A longer way to assign an addition value to a variable.


Var num = 10;
Document. write ("The value of num is:" + num); // update The value of num to 15 num = (num + 5 );
Document. write ("The new value of num is:" + num );
Var num = 10;
Document. write ("The value of num is:" + num); // update The value of num to 15 num = (num + 5 );
Document. write ("The new value of num is:" + num );

Comparison Operators

Comparison operators determine the relationship between variables or their values. You can use a comparison operator in a condition statement to compare variables or their values and calculate whether the statement is true or false to create the logic. Table 4 lists and describes all available comparison operators in the JavaScrpit language.

Table 4. Comparison Operators

Operator description

= Equal

=== Full, used for values and Object Types

! = Not equal

> Greater

<Less

> = Greater than or equal

<= Less than or equal

When writing any type of logic, the comparison of variables and values is the most basic. The example in listing 10 shows how to use the equal comparison operator (=) to determine whether 10 is equal to 1.

Listing 10. Using comparison Operators


Document. write (10 = 1 );
Document. write (10 = 1 );

Logical operators

Logical operators are usually used to combine the comparison operators in conditional statements. Table 5 lists and describes all available logical operators in the JavaScript language.

Table 5. logical operators

Operator description

&

| Or

! Non

Now you have some experience with variables and operators. It is time to learn how to create a mechanism that stores more content than simple variables.

Array

Arrays are similar to variables, but the difference is that they can put multiple values and expressions under one name. Store multiple values in one variable. This makes the array powerful. There is no limit on the type and quantity of data that can be stored in the JavaScript array. After the array is declared in the script, you can access any data of any item in the array at any time. Although Arrays can save any data type in the JavaScript language, including other arrays, the most common practice is to store similar data in the same array, specify a name associated with the array. The example provided in listing 11 uses two independent arrays to store similar data.

Listing 11. Store similar values in an array


Var colors = new Array ("orange", "blue", "red", "brown ");
Var shapes = new Array ("circle", "square", "triangle", "pentagon ");
Var colors = new Array ("orange", "blue", "red", "brown ");
Var shapes = new Array ("circle", "square", "triangle", "pentagon ");

As you can see, all these data items can be saved in an array, but this is not logical and may cause problems to the script in the future, for example, when identifying what data is stored in an array.

It is easy to access the values in the array, but there is a trap here. The array ID always starts from 0 rather than 1. You may be confused when using the array for the first time. IDS increase progressively from 0, for example, 0, 1, 2, and 3. To access an array item, you must use its ID, which points to the position of the item in the array (List 12 ).

Listing 12. Save similar values in an array


Var colors = new Array ("orange", "blue", "red", "brown ");
Document. write ("Orange:" + colors [0]);
Document. write ("Blue:" + colors [1]);
Document. write ("Red:" + colors [2]);
Document. write ("Brown:" + colors [3]);
Var colors = new Array ("orange", "blue", "red", "brown ");
Document. write ("Orange:" + colors [0]);
Document. write ("Blue:" + colors [1]);
Document. write ("Red:" + colors [2]);
Document. write ("Brown:" + colors [3]);

You can also assign a value to a position in the array or update the value of an item in the array, just like accessing the items in the array (listing 13 ).

Listing 13. assigning values to specific positions in the array


Var colors = new Array ();
Colors [0] = "orange ";
Colors [1] = "blue ";
Colors [2] = "red ";
Colors [3] = "brown ";
Document. write ("Blue:" + colors [1]); // update blue to purple colors [1] = "purple ";
Document. write ("Purple:" + colors [1]);
Var colors = new Array ();
Colors [0] = "orange ";
Colors [1] = "blue ";
Colors [2] = "red ";
Colors [3] = "brown ";
Document. write ("Blue:" + colors [1]); // update blue to purple colors [1] = "purple ";
Document. write ("Purple:" + colors [1]);

Now you have a good understanding of variables, operators, and arrays. Next you will apply what you have learned to practice and start to create some logic.

Condition Statement

A condition statement is the skeleton of various types of logic in a scripting or programming language. The JavaScript language is no exception. The condition statement is used to determine the action you want To take based on the conditions you write. The JavaScript language has four methods to write the Condition Statement. Table 6 describes this.

Table 6. conditional statements

Statement description

If a specific condition is true, the script is executed.

If... else, if a specific condition is true, a script is executed,

If the condition is false, a script is executed.

If... else, if one of the multiple conditions is true, a script is executed,

If all the conditions are false, execute other scripts.

Switch to execute one of the many scripts

If you only want to execute a script when a condition is true, use the if statement. Listing 14 shows how to use the if statement with a comparison operator to execute the script when the condition is true.

Listing 14. Using the if statement


Var num = 10;
If (num = 5 ){
Document. write ("num is equal to 5 ");
}
Var num = 10;
If (num = 5 ){
Document. write ("num is equal to 5 ");
}

If you want to execute a script when a condition is true and another script when the condition is false, use the if... else statement, as shown in listing 15.

Listing 15. Use the if... else statement

Var num = 10;
If (num = 5 ){
Document. write ("num is equal to 5 ");}
Else {
Document. write ("num is NOT equal to 5, num is:" + num );
}
Var num = 10;
If (num = 5 ){
Document. write ("num is equal to 5 ");}
Else {
Document. write ("num is NOT equal to 5, num is:" + num );
}
 

If you want to execute different scripts based on different conditions, use the if... else statement, as shown in listing 16.

Listing 16. Use the if... else statement


Var num = 10;
If (num = 5 ){
Document. write ("num is equal to 5 ");
} Else if (num = 10 ){
Document. write ("num is equal to 10 ");
}
Else {
Document. write ("num is:" + num );
}
Var num = 10;
If (num = 5 ){
Document. write ("num is equal to 5 ");
} Else if (num = 10 ){
Document. write ("num is equal to 10 ");
}
Else {
Document. write ("num is:" + num );
}

Unlike if statements, Swith statements cannot be used to determine whether the value of a variable is greater than or less than another value. The example in listing 17 shows the appropriate time to use the switch statement to determine the script to be executed.

Listing 17. Use the switch statement

Var num = 10;
Switch (num ){
Case 5:
Document. write ("num is equal to 5 ");
Break;
Case 10:
Document. write ("num is equal to 10 ");
Break;
Default:
Document. write ("num is:" + num );
}
Var num = 10;
Switch (num ){
Case 5:
Document. write ("num is equal to 5 ");
Break;
Case 10:
Document. write ("num is equal to 10 ");
Break;
Default:
Document. write ("num is:" + num );
}

 

You may have noticed that case clause, break statement, and default clause are used in listing 17. These clauses and statements are very important for the switch statement. The case clause determines whether the switch value is equal to the data value used in the clause; the break statement is interrupted -- or the rest of the statement executed by the switch statement is stopped; the default clause indicates the script to be run by default if no case statement is executed or if the executed case statement does not have a break statement. For example, listing 18 shows how multiple case statements and default statements are executed without a break statement in the executed case statement.

Listing 18. Executing multiple lines of code without the break


Var num = 10;
Switch (num ){
Case 5:
Document. write ("num is equal to 5 ");
Break;
Case 10:
Document. write ("num is equal to 10 ");
Default:
Document. write ("num is:" + num );
}
Var num = 10;
Switch (num ){
Case 5:
Document. write ("num is equal to 5 ");
Break;
Case 10:
Document. write ("num is equal to 10 ");
Default:
Document. write ("num is:" + num );
}

The result of this script is "num is equal to 10", followed by "num is: 10 ". This situation is sometimes called switch direct drop.

As mentioned at the beginning of this section, condition statements are the skeleton of all the logic in any scripting or programming language. However, if you do not need a function, your code will be messy.

Function

There are many reasons to prove that a function is useful. A function is a container of scripts that can only be executed by events or function calls. Therefore, the function is not executed when the browser initially loads and executes the scripts contained in the web page. The purpose of a function is to include the scripts to complete a task so that you can execute the script and run the task at any time.

It is easy to construct a function. It starts with the function keyword, followed by a space, followed by the function name. You can select any string as the function name. However, it is important to associate the function name with the task to be executed. Listing 19 provides a function example that modifies the value of an existing variable.

Listing 19. Construct a simple function


Var num = 10;
Function changeVariableValue () {num = 11;
}
ChangeVariableValue ();
Document. write ("num is:" + num );
Var num = 10;
Function changeVariableValue () {num = 11;
}
ChangeVariableValue ();
Document. write ("num is:" + num );

The example in listing 19 illustrates not only how to build a function, but also how to call a function to modify the value of a variable. In this example, you can modify the value of a variable because the variable is declared within the scope of the main script, and the function is the same. Therefore, the function knows the existence of the variable. However, if the variable is declared inside the function, you cannot access the variable outside the function.

Functions can also accept data through function parameters. A function can have one or more formal parameters. A function call can have one or more actual parameters based on the number of formal parameters. The formal parameters (parameter) and the actual parameters (real parameters, argument) are often mixed. The form parameters are part of the function definition, while the real parameters are the expressions used when the function is called. Listing 20 provides a function example with a form parameter. Real parameters are used for function calling.

Listing 20. Using function parameters


Var num = 10;
Function increase (_ num ){
_ Num ++;
}
Increase (num );
Document. write ("num is:" + num );
Var num = 10;
Function increase (_ num ){
_ Num ++;
}
Increase (num );
Document. write ("num is:" + num );

In this example, the function increments the value of any actual parameter passed to it. The actual parameter in this example is a variable that you have already declared in advance. By passing it as an actual parameter to the function, you increase its value to 11.

Return statements are also frequently used in functions. They return a value after the scripts in the function are executed. For example, you can assign the value returned by the function to a variable. The example in listing 21 illustrates how to return a value from a function after executing the script.

Listing 21. Use the return statement in the function


Function add (_ num1, _ num2 ){
Return _ num1 + _ num2;
}
Var num = add (10, 10 );
Document. write ("num is:" + num );
Function add (_ num1, _ num2 ){
Return _ num1 + _ num2;
}
Var num = add (10, 10 );
Document. write ("num is:" + num );

The result of this script is "num is: 20 ". The benefit of this function is that it can add any two numbers you pass to it and return the added value. You can assign this value to any variable, instead of changing the value of the same variable as listing 20.

Loop

As you have seen, arrays are a great way to store a large amount of reusable data. But this is just the beginning; for and while loops provide the ability to traverse these arrays, access their values, and use them to execute scripts.

The for loop is the most common type in JavaScript. A for Loop is usually formed in this way. First, a variable with a value is assigned, and then the variable uses a comparison operator to compare with another value. Finally, the numeric value is incremented or decreased. In a for loop, the comparison is usually to determine whether the initial variable value is smaller than or greater than another value. Then, when the condition is true, the loop runs, variable increments or decreases until the condition calculation result is false. The example in listing 22 shows how to compile a for loop, which runs cyclically when the value is smaller than the length of the array.

Listing 22. Construct A for loop and traverse an array

 

Var colors = new Array ("orange", "blue", "red", "brown ");
For (var I = 0; I {
Document. write ("The color is:" + colors [I] + "");
}
Var colors = new Array ("orange", "blue", "red", "brown ");
For (var I = 0; I {
Document. write ("The color is:" + colors [I] + "");
}

 

The length attribute of the array provides a value equal to the number of sub-items in the array. Once again, it is easy to make an error: the array ID starts from 0. Therefore, if there are four sub-items in the array, the length is 4, but the index in the array is 0, 1, 2, and 3 -- No 4.

Another type of loop is the while loop, which runs faster than the for loop, but is applicable to situations where the array is not traversed. for example, when a condition is true, a script is executed. Listing 23 shows how to write such a while LOOP, that is, when the value variable is less than 10, execute a script.

Listing 23. Constructing A while LOOP

Var I = 0;
While (I <10 ){
Document. write (I + ""); I ++;
}
Var I = 0;
While (I <10 ){
Document. write (I + ""); I ++;
}
 

It can be noted that the script in the while loop contains a line of code. This line of code overlays the numeric variable until the condition in the while loop is false. Without this line of code, you get an infinite loop.

Conclusion

The JavaScript language can be said to be one of the most popular languages. Now you understand why. This simple and rich scripting language brings about so many possibilities. It provides a powerful tool that allows website visitors to interact with the Downloaded web page. This article lays the foundation for understanding the basic principles of the JavaScript language. For now, you need to understand how JavaScript library functions work, and how to use them to simplify the coding process of the Web Client logic. The next step is to put these concepts into practice and start exploring JavaScript objects.

From tu jiankai's column
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.