Quick Start to JavaScript

Source: Internet
Author: User
Tags control characters natural logarithm

I. Basic Concepts
JavaScript is an Object-Based and Event Driver-Based scripting language. It provides a wide range of internal objects for developers.
JavaScript is an interpreted programming language. Its source code does not need to be compiled before it is sent to the client for execution. Instead, it sends the character code in the text format to the client for explanation and execution by the browser.
The following is the first JavaScript program to describe how it is embedded in the HTML document:
<Html>
<Head>
My first JavaScript!
</Head>
<Body>
This is a normal HTML document.
<Script language = "JavaScript">
<! --
Document. write ("this is displayed in JavaScript! ")
// -->
</Script>
Back in HTML again.
</Body>
</Html>
-----------------------------------------------------------------------
JavaScript code is identified by <script language = "JavaScript">... </script>. JavaScript scripts can be added between them.
Pass <! --... // --> MARK Description: if you do not know the JavaScript code browser, all the marks in it will be ignored. If you know it, the result will be executed.
Document. write () is a JavaScript window object method. Its function is to display a string of text to HTML files. There are many similar methods in JavaScript.

Ii. Data Types
JavaScript provides four basic data types to process numbers and text, as shown below:

Type

Example

Explanation

String type

"John"

A string of characters in quotation marks

Number numeric type

3.21

Any number not enclosed in quotation marks

Boolean

True or false

Only the value of either of the two can be obtained.

Null

Null

Null Value


Iii. Variables
The naming rules of variables are similar to those of other programming languages. variables can be declared or used directly in advance. The type of variables is determined by the type of the value assignment data when values are assigned:
Var mytest; // declare a variable
Var mytest = "This is a book" // define variables and assign values
X = true; // directly use
In JavaScript, global variables are defined out of all function bodies, and their scope is the entire function. Local variables are defined within the function body and are only visible to this function, other functions are invisible.

Iv. Constants
Integer constant: The value can be expressed in hexadecimal, octal, or decimal.
Real constants: they are composed of integers and decimal parts. They can also be expressed in scientific notation, such as 12.32 and 5E7.
Boolean value: true or False.
Constant type: It is represented by several characters enclosed in single or double quotation marks, for example, "Hello World ".
Null: Null, indicating nothing. For example, if you try to reference an unspecified variable, a Null value is returned.
Special characters: similar to the C language, some special characters cannot be displayed in JavaScript that begin with a backslash (/), that is, control characters.

5. Expressions and operators
JavaScript expressions are a set of variables, constants, and operators.
The JavaScript operator is similar to the C language and has a priority. However, we recommend that you use parentheses to change the execution order without relying on the priority.
JavaScript also has a single object operator, a binary operator, and a three object operator. The rule is the same as that in C.
Operator: operand? Result 1: result 2.
Binary Arithmetic Operators include: +,-, *,/, %, |, &, <, >>, >>> (right shift, zero fill ).
Single-object Arithmetic Operators include:-(inverse ),~ (Complement), ++, and ,--.
Comparison operators include: <,>, <=, >=, =, and ,! =.
Logical operators include :! , & = ,&,! =, |, ^ =, ^ ,? :, |, = ,! =.

Vi. Functions
JavaScript Functions can encapsulate the modules that may be used multiple times in a program and can be called as event-driven results to associate a function with event-driven.
The basic format of function definition is as follows:
Function Name (parameter, variable ){
Function body;
Return expression;
}
When a function is called, the variables or literal values can be passed as variable elements. The return value is returned through return. The function name is case sensitive.
The number of parameters in the function can be multiple, similar to the variable length parameter in C language. The number of parameters can be obtained through arguments. length.
JavaScript contains a number of system functions or internal methods that are irrelevant to any object. You can use these functions directly without creating any instances. For example:
Returns the value in the string expression, that is, eval (string expression), for example, test = eval ("8 + 9 + 5/2 ");
Returns the string ASCII code, that is, unEscape (string );
Returns the character encoding, that is, escape (character );
Returns a real number, that is, parseFloat (floustring );
Returns the number of different hexadecimal values, that is, parseInt (numberstring, rad. X). Where, rad. X is the hexadecimal number, and numberstring is the string number.

VII. Procedure
The Control Flow Structure of Common Programs in JavaScript is as follows:
1. if Condition Statement
Basic Format:
If (expression ){
Statement segment 1;
}
Else {
Statement Segment 2;
}
Nested format:
If (Boolean) Statement 1;
Else if (Boolean) Statement 2;
Else Statement 3;
2. for Loop statements
Basic Format:
For (initialization; condition; increment ){
Loop body statement segment;
}
3. while loop statement
Basic Format:
While (condition ){
Loop body statement segment;
}
4. break and continue statements
Similar to the C language, the break statement jumps out of the loop body and the continue statement jumps out of the current loop.

8. Use of Objects
1. Basic concepts of Objects
Objects in JavaScript are composed of two basic elements: Properties and Methods, which correspond to the variables and functions in the object-oriented model.
An object must exist before it is referenced. Otherwise, an error occurs. JavaScript can reference an object in the following three ways (create a new object or use an existing object ):
(1) Reference JavaScript internal objects;
(2) provided in the browser environment;
(3) create a new object.
JavaScript is based on objects rather than object-oriented languages. Therefore, it does not have the concepts of abstraction, inheritance, and overloading. However, it provides some statements, keywords, and operators used to operate objects:
(1) for... in statement
The format is as follows:
For (Object Property name in already has object name)
The function of this statement is to assign all the attributes of a known object to a variable in a loop instead of using a counter. The advantage is that the operation can be performed without knowing the number of attributes in the object.
For example, to traverse all elements in the array, if you use a common for loop, you need to know the number of elements in the array to control the subscript. However, this statement is much simpler:
For (var prop in object)
Document. write (object [prop]);
The code above is in the loop body, for automatically retrieves the object attributes and copies them to the prop until the loop body ends.
(2) with statement
The format is as follows:
With object {
}
In this statement body, any reference to the variable is considered to be an operation on the attributes of this object to save code.
(3) this keyword
This is a reference to the current object.
(4) new operator
Use the new operator to create a new object. The format is as follows:
Newobject = new Object (Parameters table );
Here, Object is an existing Object, Newobject is a newly created Object, Parameters table is a parameter table, and new is an operator, for example:
Birthday = new Date (December 1, 12.2014 );
Then you can use birthday as a new date object.
2. Object attribute reference
Object attribute reference can be implemented in one of the following three ways:
(1) Use the dot "." Operator
University. Name = "Hunan Province ";
University. city = "Changde city ";
University. Date = "2014 ";
(2) reference through object subscript
Universit [0] = "Hunan Province ";
University [1] = "Changde City ";
University [2] = "2014 ";
(3) Use strings to form reality
University ["Name"] = "Hunan Province ";
University ["city"] = "Changde city ";
University ["Date"] = "2014 ";
3. Reference of object Methods
The reference of object methods in JavaScript is very simple:
ObjectName. methods ();
It is easier to reference the internal object of math:
With (manth)
Document. write (cos (30 ));
Document. write (cos (90 ));
4. attributes and methods of common objects
JavaScript provides some very useful internal objects and methods. It provides string, math, and date objects and other related methods.
(1) String object
Mytest = "helloworld ";
The string object has only one attribute length, indicating the number of characters in the string.
There are 19 string objects, which are mainly used for displaying strings on the Web page, font size, font color, character search, and Case conversion of characters. The main methods are as follows:
Anchor (), for example, string. anchor (anchorName );
Character Display Control Methods: big () Large font display, italics () italic text display, bold () bold Chinese text display, blink () character flashing display, small () characters are displayed with small characters, fixed high-brightness characters are displayed with fixed (), and fontsize controls the font size.
Fontcolor method: fontcolor (color ).
String case-insensitive conversion: toLowerCase () is converted to lower case, and toUpperCase () is converted to upper case, for example: string = stringValue. toUpperCase ();
Character search: indexOf [charactor, fromIndex], that is, to search for the location where charactor appears for the first time from the specified fromIndex location.
Substring: substring (start, end), that is, all characters from start to end are returned.
(2) math object of arithmetic functions
Math objects provide some arithmetic operations except addition, subtraction, multiplication, and division, such as logarithm and square root.
Math provides six attributes, that is, the common constants E in mathematics, the natural logarithm LN10 with 10 as the base, the natural logarithm LN2 with 2 as the base, the PI of 3.14159, the square root SQRT1-2 of 1/2, and the square root SQRT2 of 2.
Math provides the following methods: absolute abs (), sin (), cosine cos (), antizheng Xuan asin (), arccosine acos (), and tangent tan () returns the arc tangent of atan (), rounded to round (), square root sqrt (), and pow (base, exponent) based on the power ).
(3) Date and Time objects
An object related to date and time must be created using the New operator, for example:
MyDate = New Date ();
The Date object does not provide direct access attributes. It only has the method of obtaining and setting the Date and time.
Start Date: 00:00:00, January 1, January 1, 1770.
Methods to obtain the date and time include getYear (), getMonth (), getDate (), getDay (), and getHours () getMintes (), getSeconds (), and getTime ().
You can set the date and time by setting the year setYear (), the current date setDate (), the current month setMonth (), the number of hours setHours (), and the number of minutes setMintes (), set the number of seconds setSeconds (), set the number of milliseconds setTime ().

IX. event-driven
JavaScript is an Object-Based language, which is different from Java. Java is an object-oriented language, and Based on the basic features of objects, event-Driven is used ). It simplifies all input in a graphic interface. Generally, the mouse or hot key action is called an Event, and the action of a series of programs triggered by the mouse or hot key is called an Event-Driven action ). The program or function that processes the Event is called the Event Handler ).
In JavaScript, Object events are usually handled by functions. The basic format is the same as that of functions. functions can be used as Event Handlers. The format is as follows:
Function event processing NAME (parameter table ){
Event Processing statement set;
}
JavaScript event-driven events are triggered by mouse or hot key actions. They mainly include the following events:
1. Click Event onClick
When you click the mouse button, an onClick event is generated. At the same time, the event handler or code specified by onClick will be called and executed. Objects that can generate this event include button (button Object), checkbox (check box or check list box), radio (single choice button), reset buttons (reset button), submit buttons (submit button), for example, you can use the following button to activate change ():
<Form>
<Input type = "button" value = "change" onClick = "change ()">
</Form>
After the onClick equal sign, you can use your own function as the event processing program, you can also use internal functions in JavaScript, or you can directly use JavaScript code, such:
<Input type = "button" value = "" onClick = alert ("this is an example") >;>
2. onChange event
This event is triggered when the input character value of the text or texturea element is changed. This event is also triggered when the status of an option in the select Table item changes. For example:
<Form>
<Input type = "text" name = "Test" value = "Test" onChange = "check (this. test)">
</Form>
3. Select event onSelect
This event is triggered when the text in the text or textarea object is highlighted.
4. Get the focus event onFocus
This event is generated when you click text, textarea, and select objects, and the object becomes the foreground object.
5. Loss of focus onBlur
This event is triggered when the text object, textarea object, and select object no longer have the focus and return to the background. This event corresponds to the onFocas event.
6. Load the file onLoad
This event is generated when a document is loaded. OnLoad is used to detect the cookie value when a document is loaded for the first time, and assign a value to it using a variable so that it can be used by the source code.
7. Uninstall the file onUnload
When the Web page exits, the onUnload Event is triggered and the cookie status can be updated.
The following is an example of automatic file loading and unloading:
<Html>
<Head>
<Script language = "JavaScript">
<! --
Function loadform (){
Alert ("start automatic loading! ");
}
Funtion unloadform (){
Alert ("start automatic uninstall! ");
}
// -->
</Script>
</Head>
<Body onLoad = "loadform ()" onUnload = "unloadform ()">
<A href = "anther.html"> go to the call page </a>
</Body>
</Html>
Open the browser and execute the above Code. When the page is loaded, the automatic loading will be executed. The "start automatic loading" dialog box will pop up. When the browser is closed, the "Start automatic unloading" dialog box will pop up.


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.