Home > Web Front-end > JS Tutorial > body text

Language Basics for Getting Started with JavaScript_Basic Knowledge

PHP中文网
Release: 2016-05-16 18:00:36
Original
958 people have browsed it

This article explains the basic principles of the language by comprehensively enumerating basic JavaScript concepts to provide beginners with a basic understanding of the language. Code examples can be found everywhere to illustrate all these concepts. How it is reflected in the language

The JavaScript language is becoming more and more popular and can be said to be one of the most prominent languages ​​on the Internet. You can use it across platforms and browsers, and it doesn't exclude back-end languages. There are many different development libraries out there - some of them really great - that are very helpful for development, speeding up development time, etc. The problem is that sometimes these libraries are very far from the original language, which makes developers who are just getting started lack a basic understanding of the language.

This article explains the basic principles of the language by comprehensively enumerating basic JavaScript concepts to provide beginners with a basic understanding of the language. Code examples can be found everywhere to illustrate all How these concepts are reflected in language.

Learn about the JavaScript language

The JavaScript language is a free client-side scripting language that allows you to navigate to Hypertext Markup Language (HTML) pages Add interactive behaviors. Client-side means that JavaScript runs in the browser rather than on the server side. Client-side scripts allow users to interact with the web page after it has been served by the server and loaded by the browser. For example, Google Maps uses JavaScript language to support interaction between users and maps. Interaction methods include moving the map, zooming in and out, etc. Without JavaScript, web pages would need to be refreshed for every user interaction, unless of course a plug-in such as Adobe Flash or Microsoft® Silverlight was used. The JavaScript language does not require plugins.

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

1. Dynamically add, edit and delete HTML elements and their value.

2. Validate the form before submitting.

3. Creates a cookie on the user's computer to save and retrieve data on future visits.

Before you start, just know a few basic principles of the language:

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

2. All JavaScript statements end with a semicolon.

3. Language is case sensitive.

4. All variable names must start with a letter or an underscore.

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

6. You can also use comments to comment out the script. To comment out multiple lines of a script, a good practice is to use /*your script goes here*/. Any scripts within asterisks will not be run during execution.

Listing 1. You need to use script tags and type attributes to include JavaScript code into HTML files


To hide JavaScript code that the browser does not support, or if the user wants to turn off the code, just use comment tags before and after the JavaScript statement (Listing 2).

Listing 2. Use comments to hide JavaScript code that the browser does not support



The most common way to include JavaScript code into a web page is to use the src attribute in the script tag to load the code from an external JavaScript file (Listing 3).

Listing 3. Including external JavaScript files in HTML files

External JavaScript files are the most common way to include JavaScript code, and there are some very practical reasons for this:

1. If your HTML pages have less code, search engines can crawl and index your site faster.

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

3. Because multiple JavaScript files can be included in the HTML code, you can separate the JavaScript files into different file directory structures on the web server, which is similar to how images are stored. This is An easier way to manage your code. Clear, organized code is always key to making website management easier.

Variables

Variables store data that will be retrieved later or updated with new data. The data stored in a variable can be a value or an 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

The result of string calculation is 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, and global variables are declared without the var keyword. A variable using the var keyword is considered local because it cannot be accessed anywhere else except the scope where you declare it. For example, if you declare a local variable inside a function (which I'll talk about near the end of the article), the variable cannot be accessed outside the function, making it local to that function. . If you declare the same variable without using the var keyword, it will be accessible throughout the script, not just within that function.

Listing 4 gives an example of a local variable named num and assigned a value of 10.

Listing 4. Declare a local variable

var num = 10;
To access the value of the num variable at another location in the script, you just Just refer to the variable by name, as shown in Listing 5.

Listing 5. Accessing the value of a variable

document.write("The value of num is: " num);


The result of this statement is "The value of num is: 10". The document.write function writes the data to the web page, and you will use this function throughout the rest of this article to write examples to the web page.

To store an arithmetic expression in a variable, you simply assign the variable to the calculated value, as shown in Listing 6. The result of the calculation is stored in the variable rather than the calculation itself. So again we get this result "The value of num is: 10".

Listing 6. Storing arithmetic expressions

var num = (5 5);
document.write("The value of num is: " num) ;


To change the value of a variable, refer to the variable by the name you assigned it and use the equal sign to assign a new value (Listing 7). The difference this time is that you don't need to use the var keyword because the variable has already 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);


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

Operators

You need operators when performing any operation in the JavaScript language. Operations include addition, subtraction, comparison, etc. There are four operators in the JavaScript language.

1. Arithmetic

2. Assignment

3. Comparison

4. Logic

Arithmetic operators

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

Table 2. Arithmetic operators

Operator description

Addition

- Subtraction

* Multiplication

/ Division

% modulo (find the remainder)

Increment

--Decrease
Assignment operator

Arithmetic operators perform basic mathematical operations, while assignment operators assign values ​​to JavaScript variables. When you assigned values ​​to variables in the previous section, you already saw the most commonly used assignment operators. Table 3 lists and describes all assignment operators available in the JavaScript language.

Table 3. Assignment operator

Operator description

=equal to

= assign the addition value (the result value of the variable plus the value) to Variable

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

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

/=Assign the division value (the result of dividing the variable by the value) to the variable

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

You've seen how to use the equal sign to assign a value or expression to a variable, but now I'll show you how to use a slightly confusing assignment operator. Assigning an additive value to a variable may be a strange concept, but it's actually quite 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);


The result of this script is "The value of num is: 10" followed by ""The new value of num is: 15". You can see that the operator in this script assigns the added value Given a variable. This can also be thought of as a shorthand version of the script written in Listing 9.

Listing 9. A longer way of assigning the added 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);


Comparison operators

Comparison operators determine the relationship between variables or their values. You use comparison operators in conditional statements to create logic by comparing variables or their values ​​to determine whether a statement is true or false. Table 4 lists and describes all comparison operators available in the JavaScript language.

Table 4. Comparison Operators

Operator Description

==Equals

=== Congruent, for value and object types

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Comparison of variables and values ​​is fundamental when writing any kind of logic. The example in Listing 10 shows how to use the equals comparison operator (==) to determine whether 10 is equal to 1.
Listing 10. Using comparison operators

document.write(10 == 1);
Logical operators

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

Table 5. Logical operators

Operator Description

&& and

|| or

! Not

Now that you have some experience with variables and operators, it's time to learn how to create a mechanism that stores more than a simple variable.

Array

Arrays are similar to variables, but the difference is that they can hold multiple values ​​and expressions under one name. Storing multiple values ​​in a variable makes arrays powerful. There are no restrictions on the type or amount of data you can store in a JavaScript array. Once you declare the array in your script, you can access any data from any item in the array at any time. Although arrays can hold any JavaScript data type, including other arrays, the most common approach is to store similar data in the same array and give it a name that is relevant to the array item. Listing 11 provides an example that uses two separate arrays to store similar data.

Listing 11. Storing similar values ​​in an array

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


As you can see, it is possible Storing all these data items in an array is illogical and may cause problems for the script later, such as identifying what data is stored in the array.

Accessing values ​​in an array is easy, but there is a catch. Array IDs always start from 0 rather than 1, which may be a little confusing the first time you use it. The ID starts from 0 and increases, such as 0, 1, 2, 3, etc. To access an array item you must use its ID, which points to the position of the child in the array (Listing 12).

Listing 12. Saving 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]);


You can also assign a value to a certain position in the array, or update the array. The value of an item in the array, just as we did earlier to access the item in the array (Listing 13).

Listing 13. Assigning a value to a specific position 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]);


Now that you have a good understanding of variables, operators, and arrays, put what you've learned into practice and start creating some logic.

Conditional statements

Conditional statements are the skeleton for creating various types of logic in scripting languages ​​or programming languages, and the JavaScript language is no exception. Conditional statements determine the action to be taken based on the conditions you write. The JavaScript language has four ways to write conditional statements, which are described in Table 6.

Table 6. Conditional statement

Statement description

if execute the script if a certain condition is true

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

If the condition is false, a script will be executed.

if...else if...else If there is no limit to the number If one of the multiple conditions is true, execute a certain script.

If all the conditions are false, execute other scripts.

switch Execute one of many scripts

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

Listing 14. Using if statement

var num = 10;
if(num == 5)
{
document.write( "num is equal to 5");
}


If you plan to execute one script when a certain condition is true and another script when the condition is false , then use the if...else statement, as shown in Listing 15.

Listing 15. Using 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);
}


If you want to execute different scripts based on different conditions, use if...else if...else statements, as shown in Listing 16.

Listing 16. Using if...else 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);
}


Swith statement is different from if statements, they cannot be used to determine whether a variable value is greater or less than another value. Listing 17 gives an example of using a switch statement to determine the appropriate time for a script to be executed.

Listing 17. Use switch statement

Copy code The code is as follows:


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 Listing 17 uses case clauses, break statements, and default clauses. These clauses and statements are very important parts of the switch statement. The case clause determines whether the value of the switch is equal to the data value used in the clause; the break statement interrupts—or stops—the execution of the remainder of the switch statement; and the default clause indicates whether the case statement is executed without , or the executed case statement does not have a break statement, the script will be run by default. For example, Listing 18 illustrates how multiple case statements and default statements are executed if there is no break statement in the executed case statement.

Listing 18. Executing multiple lines of code without breaking

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 first the sentence "num is equal to 10", followed by the sentence "num is: 10". This situation is sometimes called a straight switch.

As mentioned at the beginning of this section, conditional statements are the backbone of all logic in any scripting or programming language, but without functions, you end up with code that looks like a tangled mess. A mess.

Functions

There are many reasons why functions are useful. Functions are containers for scripts that can only be executed by events or function calls. Therefore, functions are not executed when the browser initially loads and executes the script contained in the web page. The purpose of a function is to contain scripts that perform a task so that you can execute the script and run the task at any time.

Constructing a function is easy by starting with the keyword function, followed by a space, and then the name of the function. You can choose any string to use as the name of the function, but it is important that there is some connection between the name of the function and the task it is supposed to perform. Listing 19 shows an example of a function that modifies the value of an existing variable.

Listing 19. Building a simple function

var num = 10;
function changeVariableValue()
{
num = 11;
}
changeVariableValue();
document.write("num is: " num);


The example in Listing 19 not only illustrates how to build a function, It also shows how to call functions to modify the values ​​of variables. In this example you can change the value of the variable because the variable is declared in the main script scope, as is the function, so the function knows about the variable's existence. However, if a variable is declared inside a function, you cannot access the variable from outside the function.

Function 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 of the function. Formal parameters (parameters) and actual parameters (arguments) are often confused; formal parameters are part of a function definition, while actual parameters are expressions used when calling a function. Listing 20 shows an example of a function that takes formal parameters and the function call uses actual parameters.

Listing 20. Using function parameters

var num = 10;
function increase(_num)
{
_num;
}
increase(num);
document.write("num is: " num);


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

The return statement is also commonly used in functions. They return a value after executing the script in the function. For example, you can assign the value returned by a function to a variable. The example in Listing 21 shows how to return a value from a function after executing the script.

Listing 21. Using the return statement in a function

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 nice thing about this function is that it can add any two numbers you pass it and return the added value, which you can assign to any variable instead of always changing the same one like in Listing 20. The value of the variable.

Loop

As you have already seen, arrays are a great way to store large amounts of reusable data. But that's just the beginning; for and while loops provide the functionality to iterate through these arrays, access their values, and use them to execute scripts.

The most commonly used loop type in JavaScript language is the for loop. A for loop is usually structured like this: a variable is assigned a numeric value, then the variable is compared with another value using a comparison operator, and finally the numeric value is incremented or decremented. The comparison in a for loop usually determines whether the value of the initial variable is less than or greater than another value. Then, during the period of time when the condition is true, the loop runs, and the variable is incremented or decremented until the condition evaluates to false. Listing 22 gives an example of how to write a for loop that runs when the value is less than the length of the array.

Listing 22. Constructing a for loop and traversing an array

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 items in the array. Again, the thing that can easily make you go wrong here is that the ID of the array starts from 0, so if If there are 4 items in the array, the length is 4, but the indices in the array are 0, 1, 2, and 3—there is no 4.

Another type of loop is the while loop. They execute faster than the for loop, but are suitable for situations where arrays are not traversed, such as executing a script when a certain condition is true. Listing 23 shows how to write a while loop that executes a script when a numeric variable is less than 10.

Listing 23. Constructing a while loop

var i = 0;
while(i<10)
{
document.write(i " ");
i ;
}


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

Conclusion

The JavaScript language can be said to be one of the most popular languages, and now you understand why. This simple yet rich scripting language brings so many possibilities, and it provides tools that allow website visitors to interact with downloaded web pages, which is very powerful. This article laid the foundation for understanding the basic principles of the JavaScript language. Now it should be easier for you to understand how JavaScript library functions work and how to use them to simplify the process of writing web client logic. The next thing to do is to put these concepts into practice and start exploring JavaScript objects.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template