JavaScript is a lightweight programming language.
JavaScript is a programmatic code that can be inserted into an HTML page.
When JavaScript is inserted into an HTML page, it can be performed by all modern browsers.
JavaScript is easy to learn.
first, how to write?
1.JavaScript code existence form
<!--way one--><script type= "Text/javascript" src= "js file" ></script> <!--mode two--><script Type= "Text/javascript" > JS Code content </script>
2.JavaScript Storage location
The script in the HTML must be between the <script> and </script> tags.
The script can be placed in the <body> and
Because the HTML code is executed from top to bottom, if the JS code in the head is time consuming, it will cause the user to be unable to see the page for a long time, if it is placed at the bottom of the body code block, even if the JS code is time consuming, it will not affect the user to see the page effect.
Here, the recommendation is placed at the bottom of the body body;
3. Notes
JavaScript does not execute annotations.
We can add comments to explain JavaScript, or to improve the readability of the code.
Single-line comments begin with//.
Output title: document.getElementById ("myH1"). Innerhtml= "Welcome to my homepage";//Output paragraph: document.getElementById ("MyP"). Innerhtml= " This is my first paragraph. ";
Multiline comments start with/* and end with */.
/* The code below will output a heading and a paragraph that will represent the start of the home page */
Second, the variable
The declaration of a variable in JavaScript is a very error-prone point, a local variable must start with a Var, and if Var is not used, the default is to declare a global variable.
JavaScript variables can be used to hold values (such as x=5) and expressions (such as z=x+y).
var x=5;var y=6;var Z=x+y;
Variables can use short names (such as x and y), or they can use better descriptive names (such as age, Sum, totalvolume).
- Variables must start with a letter
- Variables can also start with the $ and _ symbols (although we do not recommend this)
- Variable names are case sensitive (Y and y are different variables)
Both JavaScript statements and JavaScript variables are case-sensitive.
<script type= "Text/javascript" > //global variable name = ' Seven '; function func () { //local variable var age =; global variable gender = "Male" }</script>
third, the data type
The data types in JavaScript are divided into primitive types and object types:
- Original type
- Digital
- String
- Boolean value
- Object type
1. Digital
In JavaScript, integer values and floating-point values are not distinguished, and all numbers in JavaScript are represented by floating-point numbers.
Transformation:
- parseint (..) Converts a value to a number, or Nan if unsuccessful
- Parsefloat (..) Converts a value to a floating-point number, or Nan if unsuccessful
Special values:
- NaN, not a number. Can be judged using IsNaN (num).
- Infinity, infinitely large. Can be judged using isfinite (num).
2. String
A string is an array of characters, but in JavaScript the string is immutable: You can access text anywhere in the string, but JavaScript does not provide a way to modify the contents of a known string.
Common features:
Obj.length gets the current string length
Obj.trim () Remove whitespace
Obj.trimleft ()
Obj.trimright)
Obj.charat (n) returns the nth character in a string
Obj.concat (value, ...) stitching
Obj.indexof (Substring,start) sub-sequence position
Obj.lastindexof (Substring,start) sub-sequence position
Obj.substring (from, to) gets the---starting position and ending position of the subsequence according to the index
Obj.slice (start, end) slice
Obj.tolowercase () Uppercase
Obj.touppercase () lowercase
Obj.split (delimiter, limit) split
Obj.search (regexp) matches from the beginning, returning the first position where the match was successful (G invalid)
Obj.match (regexp) Global Search, if there is a G in the regular means find all, otherwise only find the first one.
Obj.replace (RegExp, replacement) is replaced, and g in the regular replaces all, otherwise only the first match is replaced.
$ number: Matches the nth group content;
$&: Current matching content;
$ ': text located to the left of the matched substring;
$ ': Text on the right side of the matching substring
$$: Direct Volume $ symbol
3. Boolean type
The Boolean type contains only true and false, unlike Python, whose first letter is lowercase.
- = = Compare Values equal
- ! = does not equal
- = = = Comparison value and type are equal
- !== Not equal to
- || Or
- && and
4. Arrays
The array in JavaScript is similar to the list in Python.
Common features:
Obj.length the size of the array Obj.push (ele) tail Appends the element Obj.pop () tail Gets an element Obj.unshift (ele) The head insert Element Obj.shift () Head remove Element Obj.splice (start, DeleteCount, Value, ...) Inserts, deletes, or replaces elements of an array obj.splice (n,0,val) specifies the position of the insertion element Obj.splice (n,1,val) specifies the position of the replacement element Obj.splice (n,1) Specify location Delete element Obj.slice () slice obj.reverse () invert obj.join (Sep) joins the array elements to construct a string Obj.concat (Val,..) Concatenate array obj.sort () to sort the elements of a group
Iv. Summary of small knowledge1. Serialization
Serialization is the conversion of data types in JavaScript into strings, while deserialization is reversed;
var a= "ss"; ret = Json.stringify (a);//serialization of Console.log (ret); Console.log (Json.parse (ret));//deserialization
The results are as follows:
2. Escaping
Generally use the escape of characters in the URL, and then look at the specific usage
var a= ' http://www.baidu.com?name=, Console.log (encodeURI (a)); Console.log (decodeURI (encodeURI (a))); Console.log (encodeURIComponent (a)); Console.log (decodeURIComponent (encodeURIComponent (a)));
The results are as follows:
3. Eval
Eval in JavaScript is a collection of eval and exec in Python that compiles code and can get return values.
Console.log (eval (' 1+2*5 ')); Console.log (eval (a = 1));
The results are as follows:
4. Time
In JavaScript, Date
objects are used to represent dates and times. Time-related operations are available in JavaScript, which are time-to-get and set-up time, in two time operations, in unified Time (UTC), and local time (East 8)
var now = new Date (); Now.getfullyear (); 2016now.getmonth (); month, note that the month range is 0~11,6 for July now.getdate (); Date Now.getday (); Indicates the day of the Week now.gethours (); 24-hour system now.getminutes (); Min Now.gettime (); Timestamp in number form
The results are as follows:
v. LOOPS and conditional statements
1. Conditional Statements
if (condition) { }else if (condition) { }else{ } switch (name) {case ' 1 ': Age = 123; break; Case ' 2 ': Age = 456; break; Default: Age = 777; }
2.for loops and while loops
For loop
When looping, the elements of the loop are indexed
<! DOCTYPE html>
Execution Result:
While loop, with a while loop in Python
while (condition) { }
Five, function
1. Function TypeThe functions in JavaScript can be basically divided into three categories: ordinary function, anonymous function, self-executing function.
It is also important to note that for JavaScript function parameters, the number of actual arguments may be less than the number of formal parameters, and the special values within the function arguments all the actual parameters.
function func (ARG) { return arg+1 } var result = func (1) console.log (result);//normal function: function func () { }//anonymous function: function func (ARG) { return arg+1 } setinterval ("func ()"); SetInterval (function () { console.log (123); },5000) //self-executing function (creating functions and Automating): (ARG) { Console.log (ARG); }) (1) The self-executing function is equivalent to the following code: function func (ARG) { console.log (ARG); } Func (1)
2. Function ScopeScopes are very important in many programming languages.
In general, the name used in a program code is not always valid/available, and the scope of the code that qualifies the name for its usability is the name.
The use of scopes improves the locality of the program logic, enhances the reliability of the program, and reduces the name collisions.
First, understand the scope of the other languages:
- Other languages : scoped to code block
public void Func () { if (1==1) { string name = ' Java '; } Console.WriteLine (name); } Func () //Error
- python: Using functions as scopes
Scenario One: def func (): if 1==1: name = ' Alex ' print (name) func () //Success Scenario two: def func (): if 1==1: name = ' Alex ' print (name) func () print (name) //Error
The scope of JavaScript has the following characteristics:
2.1 Using functions as scopesLet's look at the following code:
var name= ' cc '; function func () { console.log (name); if (1==1) { var name = ' DD '; } Console.log (name);} Func ()
The first sentence output is: undefined, not cc;
The second sentence outputs: DD
You may think that the first sentence will output CC, because the code has not executed var name= ' DD '; so it will definitely output cc;
As we've said above, JavaScript is scoped as a function. In fact, the above code can be rewritten:
var name= ' cc '; function func () { var name; Console.log (name); if (1==1) { var name = ' DD '; } Console.log (name);} Func ()
The name declaration overrides the global name but has not yet been assigned, so the output is undefined;
2.2 The scope of the function has been created before the function is calledfunction func () { if (1==1) { var name = ' CC '; } Console.log (name);}
the scope of the 2.3 function has a scope chain and is also created before being calledLet's take a look at the first example:
XO = "CC"; function func () { var xo = ' Eric '; function inner () { var xo = ' Tony '; Console.log (XO); } Inner ()}func ()
Output: Tony;
Comment out var xo= ' Tony '; line, output: Eric;
Also comment out var xo= ' Tony '; and Var xo= ' Eric '; output cc;
Example two: xo = "CC"; function func () { var xo = ' Eric '; function inner () { console.log (XO); } return inner; } var ret = func () ret () example three: xo = "Alex"; function func () { var xo = ' Eric '; function inner () { console.log (XO); } var xo = ' Tony '; return inner; } var ret = func () ret ()
2.4 local variable declaration in function in advancefunction func () { console.log (name);} Func ();//Program Direct error function func () { console.log (name); var name = ' CC ';} In the process of interpretation: Var name;func ();//undefined
3. JavaScript Advanced knowledge-lexical analysis
JS Run before a similar compilation process is lexical analysis, lexical analysis is mainly three steps:
The steps are as follows:
The function receives the form parameter, adds to the AO attribute, and this time value is undefine, for example ao.age=undefined;
Receives the arguments, adds the attributes to the AO, overwriting the previous undefined;
If the AO has no age attribute in the previous analysis parameter, the AO attribute is added as undefined, or ao.age=undefined;
If the AO above already has the age attribute, then no modification is made;
This may not be very understanding, the following combination of specific examples to see:
3.1 Example 1:
<script> function T1 (age) { console.log (age); var age =; Console.log (age); Function age () {} Console.log (age); } T1 (3);</script>
Lexical Analysis phase:
1) First, the active object, the Ao object, is formed;
2) First step analysis parameter:
ao.age=undefined;
An incoming argument is an overlay of ao.age=undefined: ao.age=3;
3) The second step is to analyze the local variables:
There is Var age=27;
This time follows if the Ao.age exists value then no modification is made. Follow the final result of the first step analysis Ao.age = 3, so there is no modification here: Ao.age = 3
4) Step three: the Declaration of the analysis function:
Because the function age () {} function exists
So, according to the rules, the function should be assigned to ao.age. Ao.age = 3 that covers the second step of the analysis:
Ao.age = function Age () {}
Implementation phase:
When you execute the T1 function, to Console.log (age), the last ao.age= function of the lexical analysis is () {}, so it prints:
Function age () {}
var age=27; Assign an age value of 27
At this time of the second Console.log age has been re-assigned to 27, so this time it will print:
27
function age () is not called so it does not execute
By the third Console.log (age), the value of the age has not been modified again, so this time it will print:
-
Running JS View results are exactly the same as our analysis:
3.2 Code Example 2:
function T1 (age) { var; Console.log (age); var age =; Console.log (age); Function age () {} Console.log (age); } T1 (22)
Lexical Analysis phase:
Ao.age = Undefine
An incoming argument overwrites the Ao.age=undefine:
Ao.age = 22
The first step in the last get ao.age = 22
So here Var age, and var age = 23, because the Ao.age attribute already exists value, so this time follow if there is no modification, that is:
Ao.age = 22
Because the function age () {} function exists
So, according to the rules, the function should be assigned to ao.age. Ao.age = 22 that covers the second step of the analysis:
Ao.age = function Age () {}
Implementation phase:
When you execute the T1 function, to Console.log (age), the last ao.age= function of the lexical analysis is () {}, so it prints:
Function age () {}
var age=23; Assign an age value of 23
At this time of the second Console.log age has been re-assigned to 23, so this time it will print:
23
function age () is not called so it does not execute
By the third Console.log (age), the value of the age has not been modified again, so this time it will print:
23
Running JS View results are exactly the same as our analysis:
3.3 Code Example 3
function T1 (age) { var; Console.log (age); age = All; Console.log (age); Function age () { console.log (age); } Age (); Console.log (age)}t1 (22)
Lexical Analysis phase:
Ao.age = Undefine
An incoming argument overwrites the Ao.age=undefine:
Ao.age = 22
The first step in the last get ao.age = 22, so here to follow, if the Ao.age existence value is not made any modification is:
Ao.age = 22
Because the function age () {Console.log (age)} function exists
So, according to the rules, the function should be assigned to ao.age. Ao.age = 22 that covers the second step of the analysis:
Ao.age = function Age () {Console.log (age)}
Implementation phase:
When you execute the T1 function, to Console.log (age), the final ao.age= function of the lexical analysis () {Console.log (age)} is printed:
Function age () {Console.log (age)}
Age = 23, this time overwrites the original function-age () {console.log}, so the second console.log will print:
23
function age () is a functional expression, so no action is done
Age () At this time is not a function expression, so there will be an error.
Running JS View results are exactly the same as our analysis:
Vi. Object-oriented
1. Create an Object
function Foo (n) {//constructor this.name = N;//this is equivalent to the Python object-oriented self this.sayname = function () { Console.log ( this.name);} } var obj1 = new Foo (' we '); To create an instance of an object, you must use the new operator obj1.nameobj1.sayName () var obj2 = new Foo (' Wee '); Obj1 Obj2 are all instances of Foo Objects obj2.nameobj2.sayName ()
Disadvantages of constructors: When creating each instance with a constructor, the methods in the constructor are recreated on each instance, which wastes memory;
2. Prototypes
To solve these problems, JavaScript introduces a prototype-prototype;
Each function we create has a prototype (prototype) attribute, which is an object;
Purpose: Contains properties and methods that can be shared by all instances of a particular type;
Understanding: Prototype is the prototype object of the object created by invoking the constructor;
The advantage of using prototypes is that you can have all object instances share the properties and methods that it contains;
That is, instead of defining object information (Properties/methods) in the constructor, you can add the information directly to the prototype;
function Foo (n) { this.name = n;} # Foo's prototype Foo.prototype = { ' sayname ': function () { console.log (this.name) }}obj1 = new Foo (' we '); O Bj1.sayname () Obj2 = new Foo (' Wee ');
Specific reference to http://www.jb51.net/article/63876.htm
Web front-End Basics-(c) JavaScript basic operations