Objective
JavaScript is a scripting language belonging to the Web, and is used by millions of of pages to improve design, validate forms, detect browsers, create cookies, and more.
How to write 1. Existence form
Method One: Exists in the JS file, which is written in the JS file, referenced in the current HTML
Tip: External scripts cannot contain <script> tags.
<script type "Text/javascript" src= "JS file" ></script>
Mode two: present in the current page, which is written in the current. html file
<script type "Text/javascript" > JS Code content </script>
2. Storage location
Position one: In the head tag code block
Features: The JS code placed in the head tag is loaded before the HTML body code. Therefore, if you load the JS file or link slow, it will affect the page display.
<! DOCTYPE html>
Position two: Body tag bottom (recommended)
Features: After loading the body part, the final Load JS section. So this method is better than the first method and the presentation is more friendly.
3. NotesSingle-line comments in JS use//, multiline comments using/* */
4. VariablesThe 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.
It is important to note that if a global variable declaration is made in a function, the variable is declared only after the function executes. The variable is in the undefined state before it is executed
<script> //global variable name = ' Seven '; function func () { //local variable var age =; global variable gender = "Male" }</script>
5. Semicolon
Semicolons are used to separate JavaScript statements.
Usually we add semicolons at the end of each executable statement.
Another useful use of semicolons is to write multiple statements in one line.
Tip : You may also see cases with no semicolons. In JavaScript, concluding sentences with semicolons are optional, but recommended!!
Data type 1. DigitalIn 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).
More numerical calculations:
Constant MATH.E //constant E, base of natural logarithm. the natural logarithm of the math.ln10//10. the natural logarithm of the MATH.LN2//2. math.log10e //logarithm of E of base 10. MATH.LOG2E //logarithm of E of base 2. Math.PI //constant figs/u03c0.gif. Math.sqrt1_2 //2 squared eradication with 1. Math.sqrt2 The square root of//2. The static function Math.Abs () //calculates the absolute value. Math.acos () //calculates the inverse cosine value. Math.asin () //calculates the inverse chord value. Math.atan () //calculates the inverse tangent value. Math.atan2 () //calculates the angle from the x-axis to a point. Math.ceil () //rounding on a number. Math.Cos () //calculates the cosine value. Math.exp () //calculates the exponent of E. Math.floor () //To a number of people. Math.log () //calculates the natural logarithm. Math.max () //Returns the larger of two numbers. Math.min () //Returns the smaller of the two numbers. Math.pow () //Calculates XY. Math.random () //Calculates a random number. Math.Round () //rounds to the nearest integer. Math.sin () //calculates the sine value. MATH.SQRT () //calculates the square root. Math.tan () //calculates the tangent value.
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 .
String method:
obj.length length Obj.trim () Remove Blank 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) Get sub-sequence Obj.slice (start, end) slice obj.tolowercase () uppercase Obj.touppercase () based on index The lowercase obj.split (delimiter, limit) split Obj.search (regexp) matches from the beginning, returning the first position where the match succeeded (G invalid) Obj.match (rege XP) Global Search, if there is a G in the regular means find all, otherwise only find the first one. Obj.replace (regexp, replacement) replaced, there is g in the regular replaces all, otherwise only the first match, $ number: matches the nth group content; $&: The content of the current match; $ ': text that is located to the left of the matched substring; $ ': Text on the right side of the matching substring $$: Direct amount $ symbol
3. Boolean type
Boolean (logic) can have only two values: TRUE or FALSE.
-
- = = Compare Values equal
- ! = does not equal
- = = = Comparison value and type are equal
- !=== Not equal to
- || Or
- && and
4. Arrays
4.1. Array Creation method
Law 1:var cars=["Audi", "BMW", "Volvo", 2:var cars=new Array (), cars[0]= "Audi"; cars[1]= "BMW"; cars[2]= "Volvo"; Law 3:var Cars=new Array ("Audi", "BMW", "Volvo");
4.2. Common methods for arrays
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 () array elements common methods for sorting arrays
Other 1. Serialization and deserialization
- Json.stringify (obj) serialization
- Json.parse (str) deserialization
Case code
A = {"K1": 1, "K2": 3}a["K1"] //out:1json.stringify (a) //out: "{" K1 ": 1," K2 ": 3}" B = json.stringify (a) /// Out: "{" K1 ": 1," K2 ": 3}" Json.parse (b) //out:object {k1:1, k2:3}
JSON serialization and deserialization2. Escaping
- decodeURI () characters that are not escaped in the URL- only conversion url parameter section
- decodeURIComponent () The escaped character in the URI component- escapes the entire URL
- encodeURI () escape character in Uri- only conversion url parameter section
- encodeURIComponent () escapes the characters in the URI component- escapes the entire URL
var url= "http://www.cnblogs.com?n= old boy" a = encodeURI (URL) alert (a) //"http://www.cnblogs.com?n=%E7%8E%8B%E5%AE% 9d%e5%bc%ba "b = decodeURI (a) //" http://www.cnblogs.com?n= old boy "c = encodeuricomponent (URL)//" http%3a%2f% 2fwww.cnblogs.com%3fn%3d%e7%8e%8b%e5%ae%9d%e5%bc%ba "decodeURIComponent (c)//" http://www.cnblogs.com?n= old boy "
escaped
- Escape () escapes the string
- Unescape () to escape string decoding
- Urierror is thrown by URL encoding and decoding methods
3. Regular Expressions 4. Time processing
D = new Date ()//Create current Time object date 2016-08-18t07:58:21.537zd.getfullyear () // get Year 2016d.gethours () //Acquisition: 15d.getutchours () // get Greenwich Time zone: 7 d.getminutes () //Get minutes: 58d //date 2016-08-18t07 : 58:21.537zd.setminutes (D.getminutes () +) //set-up time delayed 60 Minutes 1471510701537
5.eval
Eval in JavaScript is a collection of eval and exec in Python that compiles code and can get return values.
- Eval ()
- Evalerror executing JavaScript code in a string
Statements and exceptions
1. Conditional statements
if(condition) {}Else if(condition) {}Else{} switch (name) { case'1': Age= 123; Break; case'2': Age= 456; Break; Default:age= 777; Conditional statements in}js
conditional statements in JS
2. Looping statements
if(condition) {}Else if(condition) {}Else{} switch (name) { case'1': Age= 123; Break; case'2': Age= 456; Break; Default:age= 777; Conditional statements in}js
the loop statement in JS
3. Exception Handling
Try { // This code runs from top to bottom, where any one of the statements throws an exception the code block ends running}catch (e ) {/// If an exception is thrown in a try code block, The code in the catch code block is executed. //e is a local variable that points to the error object or other thrown object}finally { // The finally code block is always executed, regardless of whether the code in the try is thrown abnormally (even if there is a return statement in the try code block). }// Active run out exception throw new error (' error message xxxxxx') JS in exception handling
exception Handling in JSFunction 1. Basic functions
1.1. Basic functions
function func (ARG) { return true; }
1.2. Anonymous functions
var func = function (arg) { = ...; return ret; }
1.3. Self-executing functions
(function (ARG) { console.log (ARG); }) ('123') //123 indicates the parameter passed in
2. Parameters of the function arguments
In the function code, with special object arguments, the developer can access them without having to explicitly specify the parameter names.
function Sayhi () { alert (arguments.length) if"bye") { return ; } Alert (Arguments[0]);} The arguments in JS
3. Scope
Each function in JavaScript has its own scope, and when a function is nested, a scope chain appears. When the inner-layer function uses a variable, it is based on the scope chain from the inner to the outer layer of the loop, and if it does not exist, the exception.
The scope chain has been determined before the function has been executed. This is basically consistent with the Python scope chain.
4. Closures
A "closure" is an expression (usually a function) that has multiple variables and the environment in which those variables are bound, and therefore these variables are also part of the expression.
A closure is a function, and it "remembers what's happening around". Represented as "another function" defined by "one function" body
Because the scope chain can only be found inward, the function internal variable cannot be obtained by default. A closure that gets the variables inside the function externally.
In fact: self-executing function is a use of closures, usually downloaded in the third-party JS file, mostly in self-executing function mode exists. Closures address some of the problems that may arise because of variable scopes.
5. Object-oriented
In JavaScript, objects are data that owns properties and methods. A property is a value associated with an object. Method is an action that can be performed on an object.
function Foo (name,age) {this . name = name; This. Age = age; This. Func = function (arg) { return this. Name + arg;} } var obj = new Foo (' Alex '); var ret = obj. Func ("SB"); Console.log (ret);
You need to be aware of the above code:
- Foo acts as a constructor
- This refers to the object
- When creating an object, you need to use the new
Each object in the preceding code holds an identical func function, wasting memory. Use the prototype and you can resolve the problem:
function Foo (name,age) {this . name = name; This. Age = Age;} Foo.prototype = { getinfo:function () { return this. Name + this. Age }, func:function (ARG) { return this. Name + arg;} }
Exercise: Modal dialog box
<! DOCTYPE html>Front-end JavaScript basics