JavaScript getting started tutorial (2) Basic JS knowledge

Source: Internet
Author: User
Tags bitwise operators delete key mathematical constants

Where to insert JavaScript
JavaScript can appear anywhere in HTML. Use the tag <script>... </Script>: you can insert JavaScript anywhere in the HTML document, or even before <HTML>. However, if you want to insert a file in the webpage of the declared framework (the webpage of the Framework), you must insert the file before <frameset>. Otherwise, the file will not run.
Basic Format
Copy codeThe Code is as follows:
<Script>
<! --
...
(JavaScript code)
...
// -->
</Script>

The role of the second and fourth rows is to ignore JavaScript code in browsers that do not understand the <script> flag. Generally, it can be omitted because I want to find a browser that doesn't understand the Script, and I'm afraid I don't even have it in the museum. The double Backslash "//" at the front of the fourth line is the annotation label in JavaScript and will be learned later.

Another way to insert JavaScript is to write JavaScript code to another file (this file usually uses ". js), and the format is "<script src =" javascript. the js "> </script> MARK embeds it into the document. Note: You must mark it with "</script>.
For more information, see <script>. The tag has another attribute: language (lang), indicating the language used by the script. For JavaScript, use "language =" JavaScript "".
There is also a <server> tag relative to the <script> tag. The <server> MARK contains the Server Side script. This tutorial only describes the Client Side JavaScript, that is, marking the included scripts with <script>.
If you want to execute JavaScript statements in the address bar of your browser, use the following format:
Javascript: <JavaScript Statement>
This format can also be used in the connection:
<A href = "javascript: <JavaScript Statement>">... </a>

Basic JavaScript syntax
Every JavaScript statement has a format similar to the following:
<Statement>;
The semicolon ";" is the identifier of the end of a JavaScript statement. Although many browsers now allow the use of carriage return as the end symbol, it is still good to cultivate the habit of ending with a semicolon.
Statement BLOCK statement blocks are one or n statements enclosed by braces. There are several statements in braces, but outside braces, the statement block is treated as a statement. Statement blocks can be nested. That is to say, a statement block can contain one or more statement blocks.

JavaScript Variables
What are variables literally? variables are variable quantities. From a programming point of view, variables are used to store certain or certain values. The stored value can be a number, character, or something else.
The naming of variables has the following requirements:
Only letters, numbers, and/or underscores are allowed;
It must start with a letter;
It cannot be too long (in fact, what do people like to use long and smelly names ?);
It cannot be the same as the number of Reserved JavaScript Words (Key Words, Reserved Words, which are numerous and cannot be listed one by one; all Words that can be used for JavaScript commands are Reserved Words.
Variables are case sensitive. For example, variable and Variable are two different variables. Furthermore, most commands and "objects" (see the "Object-Oriented Programming" Chapter) are case sensitive.
The prompt is to name the variable. It is best to avoid using a single letter, such as "a", "B", and "c", instead of using words that clearly express the role of the variable in the program. In this way, not only can others better understand your program, but you will soon remember the role of the variable when you want to modify the program later. The variable name is generally in lower case. If it is composed of multiple words, the first word is in lower case, and the first letter of other words is in upper case. For example, myVariable and myAnotherVariable. This is only for the sake of appearance and ease of reading, because some JavaScript commands (the word "command" will be described in a more specific way in the future) are named in this way: indexOf; charAt and so on.
Variables must be declared that they cannot be used. Otherwise, an error occurs: "undefined ". Declared variables can be used:

Var <variable> [= <value>];

Var is the first keyword we come into contact with (that is, reserved words ). This keyword is used as a declaration variable. The simplest declaration method is "var <variable>;", which prepares the memory for <variable> and assigns it the initial value "null ". If "= <value>" is added, the <variable> Custom initial value <value> is assigned to the variable.

The following data types can be used for data type variables:
An integer can only store integers. It can be a positive integer, 0, or negative integer. It can be decimal, octal, or hexadecimal. The expression of the octal number is to add "0" before the number. For example, "0123" indicates that the octal number is "123 ". In hexadecimal notation, "0x" is added: "0xEF" indicates the hexadecimal number "EF ".
Float is a "real" type that can store decimals. Data shows that some platforms do not support floating-point variables stably. Do not use the floating point type if you do not need it.
String type is a string of up to zero characters enclosed by quotation marks "and. You can decide whether to use single or double quotation marks. Similar to Chinese, the quotation marks start with and end with, and can be nested with single double quotation marks: 'Here is the "JavaScript tutorial ". 'But unlike Chinese, the nesting of quotation marks in JavaScript can only have one layer. If you want to embed more characters, you need to escape the characters:
Escape characters because some characters cannot be displayed on the screen, or the JavaScript syntax has a special purpose, you must use "escape characters" when using these characters ". Escape characters start with a slash "\": \ 'single quotation marks, \ "Double quotation marks, \ n linefeed, and \ r carriage return (only common escape characters are listed above ). Therefore, the escape character can be used to enclose multiple quotation marks: 'micro says: "Here is \" JavaScript tutorial \". "'
Boolean is often used for judgment. There are only two optional values: true (true) and false (false "). True and false are reserved words in JavaScript. They are "constants ".
Objects are described in detail in the "Object-Oriented Programming" chapter.
JavaScript does not have strict requirements on data types. Generally, you do not need to declare a type when declaring a variable. Even if the type is declared, other types of values can be assigned to the variable during the process. The Declaration type can be implemented by assigning an initial value:

var aString = '';
This defines aString as a string variable with null values. var anInteger = 0;
This defines anInteger as an integer with a value of 0.
Assign a value to a variable declaration, and assign a value to the variable at any time. The assignment syntax is:
<Variable >=< expression>;
"=" Is called "value assignment", which assigns the right value to the variable on the left. The expression is discussed in the next section.

JavaScript constants include the following:

Null is a special null value. If the variable is undefined or is not assigned a value after definition, its value is "null ". If you attempt to return a non-existent object, a null value will also appear.
NaN "Not a Number ". This value is so rare that we can ignore it. When the operation fails to return the correct value, the "NaN" value is returned. The NaN value is very special, because it is "not a number", so any number is not equal to it, or even NaN itself is not equal to NaN.
True Boolean value "true ". In general, "yes ".
False: Boolean value "false ". In general, "wrong ".

There are also a series of mathematical constants in the Math object. This will be discussed in the discussion of "Object-Oriented Programming.

Expressions and operators
Expressions are similar to definitions in mathematics. An expression is an algebraic expression that connects constants and variables with certain values. An expression can contain only one constant or one variable. Operators can be Arithmetic Operators, Relational operators, bitwise operators, logical operators, and composite operators. The following table lists these operators from high-priority to low-priority:
Brackets (X) [x] Brackets are only used to specifyArrayOfSubscript
Anti-DDoS, auto-increment, and auto-Subtraction -X Returns the opposite number of x.
! X Returns a Boolean value opposite to x (Boolean value ).
X ++ The x value is added with 1, but the original x value is still returned.
X -- The x value is reduced by 1, but the original x value is still returned.
++ X Add 1 to the x value and return the subsequent x value.
-- X The value of x is reduced by 1, and the subsequent value of x is returned.
Multiplication, division X * y Returns x multiplied by y.
X/y Returns the value of dividing x by y.
X % y Returns the modulus of x and y (x divided by the remainder of y)
Add and subtract X + y Returns the value of x plus y.
X-y Returns the value of x minus y.
Relational operation X <y x <= y
X> = y x> y
Returns true if the condition is met. Otherwise, returns false.
Equal,
Not equal
X = y Returns true if x is equal to y. Otherwise, returns false.
X! = Y Returns true if x is not equal to y. Otherwise, returns false.
Bitwise AND X & y When both digits are 1 at the same time, the current number of returned data is 1, and the other values are 0.
Bitwise OR X ^ y If one of the two digits is 0, 0 is returned. Otherwise, 1 is returned.
Bit or X | y If one of the two digits is 1, 1 is returned. If both digits are zero, 0 is returned.
Bitwise operators are usually used as logical operators. The actual operation is to convert the two operands (x and y) into binary numbers, perform the preceding operations on each digit, and then return the new binary number. Because the "true" value (usually) inside the computer is the binary number of all digits being 1, while the "false" value is the binary number of all digits being 0, therefore, bitwise operators can also act as logical operators.
Logic and X & y Returns true if both x and y are true; otherwise, returns false.
Logic or X | y Returns true if either x or y is true. returns false if both are false.
Logic and/or is sometimes called "fast and/or ". This is because when the first operand (x) can determine the result, they will ignore the value of y. For example, false & y, because x = false, regardless of the value of y, the result is always false, so this expression returns false immediately, regardless of the number of y, even y can cause errors, and the program can still run.
Condition C? X: y If condition c is true, return the value of x (execute the x statement). Otherwise, return the value of y (execute the y Statement)
Assignment,
Compound operation
X = y Assign the value of y to x and return the value assigned.
X + = y x-= y x * = y
X/= y x % = y
Add, subtract, multiply, divide, and perform the remainder operation on x and assign the result to x.


Note:All operators related to arithmetic operations cannot apply to string variables. A string can be used as a string to connect two strings.

PromptPay close attention to the operation Priority. If you do not remember the operator priority during programming, you can use parentheses (). For example: (a = 0) | (B = 0 ).

Some expressions used for value assignment can be used because they have returned values. For example, use the following statement: a = B = c = 10, you can assign values to three variables at a time.

Statement
The following describes basic JavaScript programming commands, or "statements ".

Note

Like all other languages, JavaScript comments are ignored during runtime. Annotations only provide messages to programmers.

There are two types of JavaScript comments: single-line comments and multi-line comments. A single line comment is represented by a double Backslash. When a line of code contains "//", the part after "//" will be ignored. Multi-line comments are a line to multiple lines of text enclosed by "/*" and. When the program runs at "/*", all subsequent texts are ignored until "*/" appears.

NOTE: If your program requires a draft or someone else needs to read it, comments can be of great help. Developing the habit of writing comments can save valuable time for you and other programmers, so that they don't have to spend extra time pondering your program. During program debugging, you sometimes need to replace one piece of code with another, or temporarily do not want a piece of code. In this case, the Delete key is the most taboo. What should I do if I want to return the code? It is better to use comments to "hide" the code that is not needed for the time being. It is not too late to delete the code after determining the method.

If statement If (<condition>) <Statement 1> [else <Statement 2>];
This statement is a bit like a conditional expression "? : ": When <condition> is true, run <Statement 1>. Otherwise, if the else part exists, run <Statement 2>. And "? : "The difference is that if is only a statement and does not return a value. <Condition> is a Boolean value and must be enclosed in parentheses. <Statement 1> and <Statement 2> can only be one statement. To use multiple statements, use statement blocks.

Note: See the following example: if (a == 1)
  if (b == 0) alert(a+b);
else
  alert(a-b);

This code tries to use indentation to show that else corresponds to if (a = 1), but in fact, because else is the closest to if (B = 0, this Code cannot run according to the author's idea. The correct code is: if (a == 1) {
  if (b == 0) alert(a+b);
} else {
  alert(a-b);
}

PromptA line of code is too long or involves complicated nesting. You can consider using multiple lines of text. For example, if (a = 1) is not followed by an immediate statement, instead, write a new row. The browser will not be confused. When they finish reading a row and find that they are an unfinished statement, they will continue to read. Indentation is also a good habit. When some statements are subordinate to one or two of the preceding statements, indentation can make the program easier to read and help programmers write or modify the statements.

Loop body For (<variable >=< Initial Value >;< cyclic condition >;< variable accumulation method>) <Statement>;
This statement repeats the <Statement> until the <cycle condition> is false. It works like this: first assign <variable> <initial value>, and then * determine whether <cyclic condition> (should be a condition expression about <variable>) is true, if it is true, execute the <Statement> statement, and then accumulate the <variable> according to the <variable accumulation method>. Return to "*" and repeat it. If it is not true, exit the loop. This is called a "for Loop ". The following is an example. for (i = 1; i < 10; i++) document.write(i);
This statement first assigns an initial value of 1 to I and then executes document. write (I) Statement (used to write the I value in the document, see the "Object-Oriented Programming" Chapter); I ++ at repetition, that is, adding I to 1; the loop ends when I <10 is not satisfied, that is, I> = 10. The result is "123456789" output in the document ".

Like the if statement, the <Statement> statement can only be one line. if you want to use multiple statements, you need to use statement blocks.

Different from other languages, The for loop of JavaScript does not stipulate that the variable in the loop must be incremented or subtracted by one each time. <variable accumulation method> can be any value assignment expression, such as I + = 3, I * = 2, I-= j, and so on.

Prompts that the appropriate use of the for loop can simplify a large number of regular duplicates in the HTML document, that is, the use of the for loop to repeatedly write some HTML code, to improve the speed of web page download. However, please repeat the strict test in Netscape to ensure that the web page is passed. The author has tried Netscape "Sudden Death" many times because the HTML code is repeatedly written to the document using the for loop ". There is absolutely no such thing happening in IE. If your network is only for IE, it's okay to use a lot of.

In addition to the for loop, JavaScript also provides the while loop. While (<cyclic condition>) <Statement>;
Compared with the for loop, the while loop is executed when the <loop condition> is met. The accumulation of while loops is not as strong as that of for loops. <Statement> only one statement can be used, but generally statement blocks are used, because apart from repeated execution of some statements, you also need some statements that can change the value of the variable involved in the <cyclic condition>. Otherwise, once you step into this loop, the conditions are always met and remain stuck in the loop, not available. In this case, we are used to calling it an "endless loop ". The endless loop will stop the code running at the time, the document being downloaded, and occupy a large amount of memory, which may cause a crash and should be avoided as much as possible.

Break and continue

Sometimes in the loop body, you need to immediately jump out of the loop or skip the rest of the code in the loop body to perform the next loop. Break and continue have helped us a lot.

Break;

This statement is placed in the loop body to immediately jump out of the loop.

Continue;

This statement is placed in the loop body to stop this loop and execute the next loop. If the condition of the loop does not match, it jumps out of the loop.

Example Copy codeThe Code is as follows:
For (I = 1; I <10; I ++ ){
If (I = 3 | I = 5 | I = 8) continue;
Document. write (I );
}

Output: 124679.

Switch statement

If we want to classify some data, for example, to classify students' scores by excellent, good, medium, or poor, we may use the if statement: Copy codeThe Code is as follows:
If (score> = 0 & score <60 ){
Result = 'fail ';
} Else if (score <80 ){
Result = 'pass ';
} Else if (score <90 ){
Result = 'good ';
} Else if (score <= 100 ){
Result = 'ellent ';
} Else {
Result = 'error ';
}
It seems that there is no problem, but if too many if statements are used, the program looks messy. The switch statement is the best solution to this problem. Switch (e ){
Case r1: (Note: Colon)
...
[Break;]
Case r2:
...
[Break;]
...
[Default:
...]
}

The role of this section is to calculate the value of e (e is an expression), and then follow the r1, r2 ...... When a value equal to e is found, the statement after the "case" is executed until the break statement or switch section ends ("}"). If no value matches e, run the statement following "default:". If no default block exists, the switch statement ends.

The above if segment is rewritten with switch: Copy codeThe Code is as follows:
Switch (parseInt (score/10 )){
Case 0:
Case 1:
Case 2:
Case 3:
Case 4:
Case 5:
Result = 'fail ';
Break;
Case 6:
Case 7:
Result = 'pass ';
Break;
Case 8:
Result = 'good ';
Break;
Case 9:
Result = 'ellent ';
Break;
Default:
If (score = 100)
Result = 'ellent ';
Else
Result = 'error ';
}
Here, the parseInt () method will be introduced later, and its function is to take an integer. The if statement used in the last default segment is used to avoid 100 points as an error (parseInt (100/10) = 10 ).

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.