JavaScript Getting Started Tutorial (2) JS Basics _ Basics

Source: Internet
Author: User
Tags arithmetic bitwise bitwise operators comments delete key logical operators lowercase reserved


Where to insert JavaScript
JavaScript can appear anywhere in the HTML. Using tag <script>...</script>, you can insert JavaScript anywhere in the HTML document, even before <HTML> insert. However, if you want to insert in a page that declares a frame (frames page), you must insert it before <frameset>, otherwise it will not run.
Basic format


Copy Code code as follows:

<script>
<!--
...
(JavaScript code)
...
-->
</script>

The second and fourth lines are to let browsers that do not understand <script> tag ignore JavaScript code. Generally can omit, because now want to find not understand Script browser, I am afraid even the museum is not. The double backslash "//" in the front of line four is the annotation label in JavaScript and will be learned later.

Another way to insert JavaScript is to write JavaScript code into another file (this file should normally use ". js" as an extension), and then use the format "<script src=" Javascript.js ></ Script> to embed it in the document. Note that you must use the "</script>" tag.
The reference <script> tag also has an attribute: language (abbreviated Lang), which describes the language used by the script. For JavaScript, use "language=" JavaScript "".
The reference is relative to the <script> tag, and there is also a <server> tag. The <server> tag contains a server-side script (Side). This tutorial only discusses the client side (client Side) JavaScript, which is the script that is included with the <script> tag.
If you want to execute a JAVASCRIPT statement in the address bar of your browser, use this format:
Javascript:<javascript Statement >
Such a format can also be used in a connection:
<a href= "javascript:<javascript statement >" >...</a>

JavaScript Basic Syntax
Each JavaScript has a format similar to the following:
< statements >;
where the semicolon ";" Is the identifier that the JavaScript language ends as a statement. Although many browsers now allow carriage returns to act as end symbols, it is still good to cultivate the habit of ending with semicolons.
A statement block statement block is one or n statements enclosed in curly braces "{}". Inside the curly braces is a few statements, but outside the curly braces, the statement block is treated as a statement. Statement blocks can be nested, that is, a statement block can contain one or more statement blocks.

variables in JavaScript
What is a variable literally, a variable is a variable amount; From a programmatic standpoint, a variable is a memory that is used to store some type of value. The stored values can be numbers, characters, or something else.
The name of a variable's named variable has the following requirements:
Contains only letters, numbers, and/or underscores;
begin with a letter;
Not too long (in fact, who likes to use long and smelly names?) );
Can not be with javascript reserved words (key words,reserved Words, a large number of, can not be listed in one, all the words to do JavaScript commands are reserved words) repeat.
Also, variables are case-sensitive, for example, variable and variable are two different variables. More than that, most commands and objects (see the "Object Programming" chapter) are case-sensitive.
Tip To name variables, it is best to avoid using a single letter "a" "B" "C" and so on, instead of a word that clearly expresses the role of the variable in the program. In this way, not only can other people understand your program more easily, but also you will soon remember the role of the variable when you want to modify the program later. Variable names are generally lowercase, and if they are made up of multiple words, the first word is lowercase and the first letter of the other word is capitalized. For example: MyVariable and myanothervariable. This is done only for the sake of beauty and readability, because JavaScript commands (the word "command" in a more specific way later) are named in this way: Indexof;charat and so on.
A variable needs to declare that a variable that is not declared is not available, or an error occurs: "Undefined." Declaring variables can be used:

var < variable > [= < value >];

var we touch the first keyword (i.e. reserved word). This keyword is used as a declaration variable. The simplest way to declare this is "var < variable >;", which prepares the memory for < variable > and assigns it an initial value of "null." If "= < value >" is added, the < variable > is given a custom initial value of < value of >.

Data type variables can be used with the following data types:
An integral type can only store integers. can be positive integers, 0, negative integers, can be decimal, octal, hexadecimal. The octal number is represented by adding "0" to the number, such as "0123" to denote the octal number "123". Hexadecimal is added "0x": "0xEF" to denote the hexadecimal number "EF".
A floating-point type is "solid" and can store decimals. Data show that some platforms have unstable support for floating-point variables. Do not use floating-point types if you do not need them.
The string type is 0 or more characters wrapped in quotes "" "" "" "". It's up to you to decide whether to use single or double quotes. As with Chinese, use which quotes to start with which end, and single double quotes can be nested: ' This is the JavaScript tutorial. But unlike Chinese, there is only one layer of nested quotes in JavaScript. If you want to embed some more, you need to escape the characters:
Escape characters are used when you want to use these characters, because some characters are not visible on the screen, or they have special uses in JavaScript syntax. The escape character begins with a slash "\": \ ' single quotes, \ ' double quotes, \ n line breaks, \ r return (the above lists only the commonly used escape characters). Then, using the escape character, you can do multiple nested quotes: ' This is the JavaScript tutorial \, ' Micro said. " '
Boolean is often used to determine that only two values are optional: true (table "true") and False (table "false"). True and false are reserved words for JavaScript. They belong to "constants".
Objects are discussed in detail in the "object-oriented Programming" chapter.
Because JavaScript is not strict with data types, it is generally not necessary to declare a variable without declaring the type. And even if you declare a type, you can give the variable a different type of value in the process. Declaring types can be done by using the method assigned to the initial value:




var aString = '';
This defines the astring as a string variable with a null value.
var anInteger = 0;
This defines the aninteger as an integral type with a value of 0.
variable is assigned a variable declaration, you can assign a value at any time. The syntax for assigning values is:
< variables > = < expression >;
where "=" is called "assignment", its function is to assign the value on the right to the variable on the left. The expression is discussed in the next section.

The JavaScript constants have the following:

NULL a special null value. The value of a variable is "null" when it is undefined, or if it has not been assigned any assignment after it is defined. A null value also appears when attempting to return an object that does not exist.
NaN "not a number". This number is so rare that we can ignore it. When the operation cannot 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, and even Nan itself is not equal to Nan.
True the Boolean value is true. In popular parlance, "yes".
False Boolean value "false". In popular parlance, "wrong".

There is also a series of mathematical constants in the Math object. This is discussed in the discussion of "object-oriented programming."

Expressions and Operators
Expressions are similar to definitions in mathematics, and expressions refer to algebraic expressions with certain values that are connected by operators to constants and variables. An expression can contain only one constant or one variable. The operators can be arithmetic, relational, bitwise, logical, and composite operators. The following table arranges these operators from high priority to low priority:
Brackets (x) [x] The brackets are used only to indicate the subscript of the array
Negation, self addition, self reduction -X Returns the opposite number of X
!x Returns a Boolean value that is the opposite of X (Boolean value)
X + + x value plus 1, but still return the original X value
x-- x value minus 1, but still return the original X value
++x x value plus 1, return the X value later
--x x value minus 1, return the X value later
Multiply, divide X*y Returns the value of x times y
x/y Returns the value of x divided by Y
X%y Returns the modulus of x and Y (the remainder of x divided by Y)
Add, Subtract X+y Returns the value of x plus y
X-y Returns the value of X minus y
Relational operations X<y x<=y
X>=y X>y
Returns a true value when the condition is met, otherwise it returns a value of False
Equals
Not equal to
X==y Returns a true value when x equals Y, otherwise returns a value of False
X!=y Returns a true value when x is not equal to Y, otherwise returns a value of False
Bit and X&y When two digits are at the same time 1 o'clock, the current digit of the returned data is 1, and the other is 0
Bit XOR or X^y Two digits have and only one is 0 o'clock, return 0, otherwise return 1
Bit or X|y Two digits in which only one is 1, returns 1, and returns zero when two digits are zero
Bitwise operators are often used as logical operators. Its actual operation is to convert two operands (that is, X and y) into binary numbers, perform the work listed above for each digit, and return the resulting new binary number. The bitwise operator can also act as a logical operator because the "true" value is a binary number of 1 for all digits in the computer, and a "false" value is a binary number that is all 0.
Logic and X&&y Returns True when X and Y are true, or false
Logical OR x| | Y Returns True when either X and Y are true, false when both are false
Logic and/or sometimes referred to as "fast and/or". This is because when the first operand (x) has been able to determine the result, they will ignore the value of Y. For example, False && y, because x = = False, regardless of what the value of Y is, the result is always false, so this expression returns false immediately, and no matter how much y is or even y can cause an error, the program can still run.
Conditions C?x:y Returns the value of x when condition C is true (executes the X statement), otherwise returns the values of Y (execute the y statement)
Assign Value,
Composite operations
X=y Assign the value of Y to X and return the assigned value
X+=y x-=y x*=y
X/=y x%=y
X and y Add/subtract/multiply/divide/rest, the result is assigned to X, and returned X is assigned


AttentionAll arithmetic-related operators do not work on string variables. A string can use +, + = as a connection to two strings.

TipsPlease pay close attention to the priority of the operation. You can use parentheses () when programming without remembering the precedence of operators. For example: (a = = 0) | | (b = = 0).

Some of the expressions used to assign values can be exploited because they have returned values. For example, use the following statement: a = b = c = 10, you can assign values to three variables at once.

Statement
The following will begin the discussion of JavaScript BASIC programming commands, or "statements".

Notes

Like all other languages, JavaScript annotations are ignored at run time. Comments only provide messages to programmers.

There are two types of JavaScript annotations: Single-line comments and Multiline comments. Single-line comments are represented by a double backslash "//". When a line of code has a "//", then the part after "//" will be ignored. Multiline comments are one line to multiple lines of text enclosed in "/*" and "* *". The program executes to "/*", ignoring all subsequent text until "* *" appears.

Tip If your program needs a draft, or if you need to have someone read it, the annotation can be helpful. Getting into the habit of writing notes can save you and other programmers valuable time, so they don't have to spend extra time thinking about your program. In the process of debugging, sometimes you need to change a piece of code to another paragraph, or temporarily not a piece of code. At this time the most taboo with the Delete key, if you want to return to that section of code how to do? It is best to use annotations, the temporary code "hidden" to determine the method after the deletion is not too late.

If statement
if ( <Condition>) <Statement 1> [else <Statement 2> ];
This statement is somewhat like a conditional expression "?:": Execute < Statement 1&gt when < condition > is true, otherwise, if the else part exists, the < statement 2>. Unlike "?:", if it is just a statement, it does not return a value. < Condition > is a Boolean value that must be enclosed in parentheses;< statement 1> and < statement 2> are only one statement, in order to use multiple statements, use a statement block.

Take a look at the following example:
if (a == 1)
  if (b == 0) alert(a+b);
else
  alert(a-b);
This code attempts to use the indentation method to indicate that else is the corresponding if (a = = 1), but in fact, because else is closest to if (b = = 0), the code does not work as the author thinks. The correct code is
if (a == 1) {
  if (b == 0) alert(a+b);
} else {
  alert(a-b);
}
TipsA line of code is too long, or involves more complex nesting, you can consider using multiple lines of text, as in the example above, if (a = = 1) does not immediately after the statement, but instead of a line to continue writing. Browsers are not confusing, and when they finish reading a line, they find an unfinished statement that continues to read. Using indentation is also a good habit, when some statements with the above one or two statements have dependencies, the use of indentation can make the program easier to read, to facilitate the programmer to write or modify the work.

Circulation Body
for (<Variable> = <initial value>; <loop condition>; <variable accumulation method>) <statement>;
The purpose of this statement is to repeat the execution of the < statement until the < loop condition > is false. It works like this: first give < variable > assign < initial value, and then * Judge < cyclic condition > (should be a conditional expression on the < variable >) if it is set up, execute the < statement, and then press < Variable Accumulation method > < variables > To add, back to "*" Repeat, if not set up to exit the loop. This is called "for loop." Take a look at the example below.
for (i = 1; i < 10; i++) document.write(i);
This statement first assigns an initial value of 1, then execute the document.write (i) statement (the effect is to write the value of I in the document, please refer to the "object-oriented Programming" chapter); i++ when repeated, that is, I plus 1, loop until i<10 is not satisfied, that is, i>=10 end. The result is an output of "123456789" in the document.

Like an if statement, the,< statement > can only be one line of statements, if you want to use more than one statement, you need to use a statement block.

Unlike other languages, the JavaScript for loop does not specify that the loop variable must be added one or minus one,< variable per cycle > can be any assignment expression, such as i+=3, i*=2, i-=j, etc.

Hints that the appropriate use for loop, can make the HTML document a large number of regular repeated parts of the simplification, that is, for the loop repeatedly write some HTML code, to improve the speed of downloading the Web page. But please repeat the rigorous testing in Netscape to ensure that it is passed before the page can be transmitted up. The author has tried many times to cause Netscape "sudden death" by repeatedly writing HTML code to the document with a for loop. IE in absolutely no such things happen, if your network is only for IE to see, with a lot of for also no problem.

In addition to the For Loop, JavaScript also provides a while loop.
while (<Loop condition>) <statement>;
is simpler than the For loop, while the function of the while loop is to execute < statement > when the < cyclic condition > is met. The cumulative nature of the while loop is not strong for loops. < statement > can only be a single statement, in general, however, a statement block is used because, in addition to repeating some statements, you need some statements that can change the value of the variable < cyclic conditions > The variables involved, otherwise one step into the loop will be stuck in the loop because the condition is always satisfied , can't come out. In this case, we are accustomed to call it a "dead circle". The dead loop will stop the code that was running, the document being downloaded, and the large memory footprint, which is likely to cause a panic and should try to avoid it.

Break and Continue

Sometimes in a loop, you need to immediately jump out of the loop or skip the rest of the code in the loop to make the next loop. The break and continue helped us a great favor.

Break

This statement is placed in the loop body, which acts immediately out of the loop.

Continue

This statement is placed inside the loop, which stops the loop and executes the next loop. If the condition of the loop does not match, jump out of the loop.

Cases
Copy Code code as follows:

for (i = 1; i < i++) {
if (i = = 3 | | | = = 5 | | | i = = 8) continue;
document.write (i);
}

Output: 124679.

Switch Statement

If you want to classify some of the data, for example, to classify the student's results by an excellent, good, medium, or bad, we might use the IF statement:
Copy Code code 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 = ' excellent ';
} else {
result = ' ERROR ';
}
Looks fine, but with too many if statements, the program looks a bit messy. The switch statement is the best way to solve this problem.
switch (e) {
  case r1: (Note: colon)
    ...
    [break;]
  case r2:
    ...
    [break;]
  ...
  [default:
    ...]
}
The function of this large section is to compute the value of E (E is an expression) and then follow the R1, R2 after "case" below. Compare, when a value equal to E is found, the statement after the "case" is executed until the break statement or switch paragraph end ("}") is encountered. If no value matches the E, then the statement following "default:" is executed, and if there is no default block, the switch statement ends.

The above if section is rewritten with a switch:
Copy Code code 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 = ' excellent ';
Break
Default
if (score = 100)
result = ' excellent ';
Else
result = ' ERROR ';
}
where the parseint () method is introduced later, the role is to take the whole. The IF statement used in the last default paragraph is for the purpose of not putting 100 points as Error theory (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.