Getting started with javascript

Source: Internet
Author: User

Getting started with javascript
JavaScriptI,JavaScript Overview1,What is JavaScript and what is its function? (Understanding)

* JavaScript is the most popular scripting language on the Internet.

* The scripting language cannot be used independently. It must be embedded in other languages for combination.

* JavaScript cannot be used independently. It must be used together with other languages (HTML ).

* Browser explanation execution

* Function: control the logical operations on the front-end page.

For example, JavaScript can control CSS styles (generally)

JS can verify a single table (important)

JS can dynamically control HTML elements (more)

* Features:

Security (you do not have the permission to access system files and cannot use it for Trojans)

Cross-platform (the browser has a JS parser, and JS Code can be run as long as there is a browser, it is irrelevant to the platform)

      demo1.html    
     
     
         
 <script type="text/javascript">var sum=0;// int sum=0;for(var i=1;i<=9;i++){// int i=1;sum+=i;alert(sum); //System.out.print(sum);}</script>                


2, Relationship between JavaScript and Java (understanding)

ECMAScript

* JavaScript has nothing to do with Java (Lei Feng and Lei Feng)

* Differences between JavaScript and Java:

> JavaScript code can be executed directly in the browser, but Java must be compiled before it can be executed.

> JavaScript is a weak type language, and Java is a strong type language.

Strong language: the use of variables must strictly comply with the definition. (For example, after the variable Declaration, there is a fixed area, and the size of the int area is 32 bits ). Pain in programming and comfort in BUG Tuning

Weak language: variables are strictly defined. (For example, there is no fixed region after the variable declaration, and any type of value can be placed in this region ). Programming is comfortable, debugging is painful

<Script>

Var sum = 0;

For (var I = 1; I <= 100; I ++ ){

Sum + = I;

}

Alert (sum );

</Script>

Ii. JavaScript syntax and usage (important) Note

* Single line comment

//

Myeclipse shortcut key ctrl + shift + c

* Multi-line comment

/**/

Myeclipse shortcut key ctrl + shift +/

Variable

* Indicates a space in the memory used to store data. The data is variable.

* Format:

Var variable name = variable value;

The variable declaration in JavaScript uses the var keyword.

Data Type of the variable value (original data type and reference data type)

> Raw data type:

String type

Both "" and "" indicate strings.

Boolean Type

True, false

Number numeric type

Integer and decimal number

Null indicates that the referenced object does not exist.

Undefined

When the variable declaration is not assigned a value, use/when the object's attribute is not assigned a value.

Note: variables are like a plate and can contain everything.

You can use typeof () to determine the type of a variable. Example: var str = "aa"; alert (typeof (str); // string

Variables are case sensitive. yy and YY are not variables.

Why does the typeof operator return "Object" for null values ". This is actually an error in the initial implementation of JavaScript, which is followed by ECMAScript. Now null is considered a placeholder for an object, which explains this contradiction, but technically it is still the original value.

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* var variable name = variable value; original data type: string "" ''indicates the boolean string type true, falsenumber: the integer and decimal number are null. if the object is null (the reference is empty) and the undefined variable is not assigned a value, the object is used. when the attribute is not assigned a value, you can use the // variable as a plate. You can reference the data type when loading anything: typeof () it helps us determine what type of variable names are case sensitive (case sensitive) * // * var str = "aa"; var str2 = 'a '; var str3 = true; // falsevar str4 = 15; var str5 = 15.55; var date = null; var aa; str = 15; str = true; str = "aa "; alert (str); // aa 15 * // * var str = "aa"; str = 15; // number // str = true; // booleanvar ss; var obj = null; alert (typeof (obj); * // * var sf = "aa"; alert (Sf); * // * Reference a Common Object of the Data Type: string, Array, Date, Math, RegExpObject parent Object of all objects */var date = new Date (); alert (date instanceof Object); </script>              


> Reference data type (learn more)

Object

Example: var obj = new Object ();

Common objects:

String, Array, Date, Math, RegExp

Note: instanceof can be used to determine whether an object belongs to a certain type. Returns true and false. For example:

Var str = new String ();

Alert (str instanceof String); // true

* Two variables:

> Global variables

Is the variable defined in the <script> label, which is valid throughout the page.

> Local variables

Is the variable defined in the function body.

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* The global variable is the variable in the script tag, the local variables that are valid for the entire page are the variables defined in the function body * // * var str = 10; for (var I = 1; I <= 3; I ++) {} alert (I); // 4 * // * function aa () {var a = 5; alert (a) ;}*/var x = 4; function show (x) {x = 8;} show (x); alert ("x =" + x);/* A.8 B .4 C. undefined */</script>              

Exercise: the following code shows the X value?

Var x = 4;

Function show (x ){

X = 8;

}

Show (x );

Alert ("x =" + x );

A.8

B .4

C. undefined

Function (method)

* Used for code encapsulation to improve reusability

* Function name (parameter list ){

Function body;

Return;

}

* Function Definition, keyword function

* When defining the parameter list, you do not need to use the var keyword. Otherwise, an error is returned.

* If no response parameter is required, return can be left empty.

* Functions must be called before they can be executed, Just Like Java.

* JavaScript does not have the overload form:

> Each JavaScript contains an array of arguments to store the parameter list.

Think: What will the output result be printed by calling the following method?

Function getSum (){

Return 100;

}

Var sum = getSum;

Alert (sum );

A.100

B. undefined

C. function getSum () {return 100 ;}

* If you forget to add () when calling a method, the reference of the function object will be passed to the variable.

      Pai.html    
     
     
         
 <Script type = "text/javascript"> // Method Used for addition a B a + B/* public int sum (int a, int B) {return a + B;} * // JavaScript does not define the type of the returned value. // The javascript method does not have any overload. // because arguments contains an object (array) in the JavaScript method ), is used to obtain the passed parameter list // JavaScript if the call method is not enclosed in brackets, it will pass the reference of the method (object)/* function sum (a, B) {alert (arguments. length); alert (arguments [0]); alert (arguments [1]); alert (arguments [2]); // alert (); // alert (B);} sum (100, 7); */function getSum () {return;} var sum = getSum; alert (sum); </script>          

* Two Types of extension functions:

> Dynamic functions (available)

Dynamic creation through built-in JS Object Function

Format: new Function (parameter 1, parameter 2 );

Parameter 1: List of function parameters

The second parameter is the function body.

> Anonymous functions (commonly used)

Functions with no name are simplified

Format: var str = function (parameter list ){

Function body;

Return;

};

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* dynamic Function (rarely used) Function object anonymous Function * // * var par = "a, B, c "; var par2 = "return a + B + c"; var str = new Function (par, par2); alert (str (1, 2, 3 )); */var str = function (a, B) {return a + B ;}; alert (str (1, 2); </script>              

Operator

Arithmetic Operators (commonly used)

+ In addition to operations, it can be used as a connector

-In addition to operations, the number can be used as a conversion character.

Alert (true + 1); // 2

Comparison operators (commonly used)

= Comparison value

=== Comparison value and type Statement (flow control statement)

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* Arithmetic Operators + connectors-the conversion operator NaN indicates whether the number comparison operator = is only a comparison value, it doesn't matter even if the types are different ===not only compare values, but also compare the types * // * var str = 15; var str2 = "1"; alert (str + str2 ); // 151 * // * var str = 15; var str2 = "1"; alert (str-str2); // 14 151 * // * var str = 15; var str2 = "a"; alert (str-str2); // NaN * // * var str = 8; // alert (str = 8 ); // true // alert (str = "8"); // truealert (str = 8); // truealert (str = "8 "); // false * // * var str = (8 = 8 )? 8: 0; alert (str); */</script>              

Process control statement

Expressions for program running Flow Control

N judgment statement

IF

If (8 = num ){

Pay attention to the assignment problem.

} Else {

}

0,-0, null, "", false, undefined, Or NaN, false

Otherwise, it is true.

Same as in Java.

Switch (n)

{

Case 1:

Execution Code Block 1

Break

Case 2:

Execution Code Block 2

Break

Default:

If n is neither 1 nor 2, execute this code

}

Exercise: the output result of the following code is:

Var a = 15;

If (a = 15 ){

Alert (15 );

} Else {

Alert ("else ");

}

A.15

B. Else

N loop statements

For Loop (more common)

For (var I = 0; I <= 8; I ++ ){

// Loop body

}

Enhance the FOR Loop (not flexible and rarely used, but will be used in development) (learn how to use it and try it yourself at work)

For (variable in object ){

// Loop body

}

* The variable in it represents the subscript.

* Use the in keyword

* Traverses an array (or object) and uses an array [subscript]

* Example:

Var s = new Array ();

S [0] = 1;

S [1] = 2;

For (x in s ){

Alert (s [x]);

}

While (expression ){

// Loop body

}

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* determine the IF0,-0, null, "", false, undefined, Or NaN statements, false; otherwise, true FOR loop var 99 multiplication table while do while is enhanced for * // * function str () {return null;} var x = 8; var aaaa = str (); if (aaaa) {alert (1); // 1} else {alert ("else");} * // * for (var I = 0; I <3; I ++) {} * // * if (-0) {alert (1);} else {alert ("eeee ");} */var I = new Array (); I [0] = 1; I [1] = 2; for (x in I) {alert (I [x]);} </script>              



Object

LString object (available)

* Var str = "abc ";

* Var str = new String ("abc ");

* Attribute: length of the length string

* Method

* Similar to the String object in java (basically the same, you need to exercise)

* CharAt (index) returns the characters at the specified position (commonly used)

* IndexOf (searchvalue, fromindex) retrieves a string

* LastIndexOf () from the forward

* Replace () replaces a string (more common)

* Substring (start, stop) start and end)

* Where does substr (start, length) start from and intercept the length?

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* String object var s = new String ("aaa"); var s = "aaa"; document. write (); // outputs the value to the browser page * // * var str = "abc"; var str2 = ""; document. write (str2.blink (); document. write (str2); document. write (str. charAt (1); */var str = "ABC"; document. write (str. toLowerCase (); </script>              


LArray object (important)

* Js Array

* Var arr = [1, 2, 3];

* Var arr = new Array (); the default Array length is 0.

* Var arr = new Array (4); Array length: 4

* Var arr = new Array (); the Array element is

* Array Length

* Length

* The array length is variable.

* Array elements can be of any type (note)

* Method

* Concat () can link arrays or elements (less)

* The join (separator) is converted into a string.

* Add an element to the end of push () and return the new length.

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* Array object var str = [1, 2, 3]; Length: 3; length variable var str = new Array (); the default length is 0, and the variable length var str = new Array (5); the default length is 5, the variable length var str = new Array (1, 2); the length is 2, by default, the variable-length join (separator) operation adds elements to the end of the array * // * var str = [, 3]; var str2 = [, 6]; alert (str. concat (str2); * // * var str2 = [1, 2, 3]; var str = str2.join (); alert (str); */var str2 = [1, 2, 2, 3]; var str = 5; str2.push (str); alert (str2); // </script>              


LDate object (more common)

* Var date = new Date (); current time

* ToLocaleString () is converted to a string based on the Local Date Format (for more information)

* GetDate () returns a day of the month (learn more)

* GetMonth () Get the month (0-11) (learn more)

* GetFullYear () Get year (learn more)

* GetTime () gets the number of milliseconds (important)

* SetTime () sets the date in milliseconds (important)

You can also set the new Date (in milliseconds) through the constructor );

* Date. parse (datestring) parses the string and returns the number of milliseconds (important)

* Cannot be resolved

* Can be parsed.

LMath object (understanding)

Round (x) Rounding

Random () randomly generates 0 ~ 1 digit

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* Date object var aa = new Date (); */var aa = new Date (); // alert (aa. toLocaleDateString ();/* alert (aa. getDate (); alert (aa. getMonth (); alert (aa. getFullYear (); * // * var long1 = aa. getTime (); var long2 = long1-(1000*60*60*24); aa. setTime (long2); alert (aa. toLocaleString (); */var bb = Date. parse ("2015/5/21"); // aa. setTime (bb); var cc = new Date (bb) alert (cc. toLocaleString (); </script>              


LRegExp object (important)

* Regular object rules

* Var reg = new RegExp ("expression"); (not required in development)

* Var reg =/^ expression $/direct quantity (commonly used in development)

There is a boundary in the direct quantity, that is, ^ indicates start, and $ indicates end.

* Test (string) (frequently used): returns true if the rule is met, and false if the rule is not met.

For example:

If (reg. test ("12345 ")){

//

} Else {

//

}

      Demo1.html    
     
     
         
 <Script type = "text/javascript">/* RegExp object var s = new RegExp ("expression"); var s =/^ expression $/; test () */var reg =/^ \ s * $/; // verify that empty var checkText = ""; alert (reg. test (checkText); </script>              

Exercise: judge whether the string is null

Var msg = "";

Var reg =/^ \ s * $ /;

Alert (reg. test (msg ));

L global functions

Global

The function in the browser memory is used directly.

Eval () can parse strings and execute javascript code (learning JSON) (most commonly used)

IsNaN () is not a number (commonly used)

EncodeURI () Encoding

DecodeURI () decoding

(Don't see) escape unencoded characters are 69: *, +,-,.,/, @, _, 0-9, a-z, A-Z

(Understand) encodeURI does not encode 82 characters :!, #, $, &, ', (,), *, +,-,.,/,:,;, = ,?, @,_,~, 0-9, a-z, A-Z

(Understand) encodeURIComponent does not encode 71 characters :!, ',(,),*,-,.,_,~, 0-9, a-z, A-Z

Iii. Combination of JavaScript and HTML (understanding)

L two usage methods

> Internal use

* <Script type = "text/javascript"> JavaScript code </script>

> External reference

* <Script type = "text/javascript" src = "javascript file path"> </script>

* Script code cannot be contained in the script tag during external reference, and will not be executed even if it is written.

Note: <script> labels can be written anywhere, but pay attention to the loading sequence of HTML and JAVASCRIPT.

What should I do after the webpage is loaded?

      Demo1.html    
     
     
         
 <Script type = "text/javascript"> function aa () {alert (document. getElementById (""). innerHTML); // print Hello alert ("1"); alert ("2") ;}</script>    Hi!

Iv. JavaScript composition (understanding) Composition of JavaScript

* ECMAScript (CORE)

* DOM Document Object Type

* BOM browser object type

Exercise:

1. 99 multiplication table

2. How many days are there between and?

1. Answer

<Script type = "text/javascript">

For (var I = 1; I <= 9; I ++ ){

For (var j = 1; j <= I; j ++ ){

Document. write (j + "*" + I + "=" + j * I + "\ t ");

}

Document. write ("
");

}

</Script>

2 answer: 245

<Script type = "text/javascript">

Var dlong1 = Date. parse ("2015/01/01 ");

Var dlong2 = Date. parse ("2015/09/03 ");

Alert (dlong2-dlong1)/1000/60/60/24 );

</Script>

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.