JavaScript is a programming language, the browser has built-in JavaScript interpreter, so in the browser according to the JavaScript language rules to write the corresponding code, the browser can explain and make corresponding processing.
First, how to write 1, JavaScript code existence form
<!--way one--><script type "Text/javascript" src= "js file" ></script> <!--way two--><script Type "Text/javascript" > JS code content </script>
View Code
2, JavaScript code storage location
- In the head of HTML
- The bottom of the body code block of HTML (recommended)
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.
<script src= "https://www.gstatic.com/og/_/js/k=og.og2.en_US.iF4jnkQuaf0.O/rt=j/t=zcms/m=def/exm=in,fot/d=1/ Ed=1/rs=aa2yrtv5-poc4ks9gtgrdy2ywuwisqz7-q "></script><script> alert (' 123 '); </script>
View Code
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.
<script type= "Text/javascript" > //global variable name = ' Seven '; function func () { //local variable var age =; global variable gender = "Male" }</script>
Code comments in javascript:
- Single-line//
- Multi-Line/* * *
Note: This comment takes effect only in the script block.
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
In particular, numbers, booleans, nulls, undefined, and strings are immutable.
// null, undefined null is a keyword in the JavaScript language that represents a special value that is commonly used to describe "null values". Undefined is a special value that indicates that the variable is undefined.
null and undefined
1. Numbers (number)
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).
More numerical calculations:
constant MATH.E constant E, base of natural logarithm. The natural logarithm of the math.ln1010. The natural logarithm of the math.ln22. math.log10e the logarithm of E with a base of 10. MATH.LOG2E the logarithm of E with a base of 2. MATH.PI constant figs/u03c0.gif. the square of the math.sqrt1_22 is eradicated with 1. The square root of the math.sqrt22. 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 () rounds 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 the two numbers. Math.min () returns the smaller of the two numbers. Math.pow () calculates XY. Math.random () calculates a random number. Math.Round () is rounded to the nearest integer. Math.sin () calculates the sine value. MATH.SQRT () calculates the square root. Math.tan () calculates the tangent value.
Math
2. Strings (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 length Obj.trim () removal 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 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 (regexp) 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)
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
Arrays in JavaScript are similar to lists 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. Other
1. Serialization
- Json.stringify (obj) serialization
- Json.parse (str) deserialization
2. Escape
- decodeURI () characters that are not escaped from the URL
- decodeURIComponent () non-escaped characters in the URI component
- encodeURI () escape character in Uri
- encodeURIComponent () escapes the characters in the URI component
- Escape () escapes the string
- Unescape () to escape string decoding
- Urierror is thrown by URL encoding and decoding methods
3. 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
4. Regular expressions
1. Define Regular expressions
- /.../for defining regular expressions
- /.../g represents a global match
- /.../i indicates case insensitive
- /.../m for multi-line matching
JS regex matches itself to support multiple lines, where multiple lines match only affect the regular expression ^ and $,m mode will also use ^$ to match the contents of the newline)
var pattern =/^java\w*/gm;var Text = "JavaScript is more fun than \njavaee or javabeans!"; result = pattern.exec (text) result = pattern.exec (text) result = pattern.exec (text)
Note: Defining regular expressions can also reg= new RegExp ()
2. Matching
Regular expressions are supported in JavaScript, which provides two main features:
- Test (String) checks whether the string matches the regular match
n = ' uui99sdf ' reg =/\d+/reg.test (n) ---> True # matches as long as the regular is present in the string, and if you want to match the beginning and the end, you need to add ^ and $ to it before and after the regular
- EXEC (String) Gets the contents of the regular expression match, if it does not match, the value is null, otherwise, gets the array that matches successfully.
gets the contents of the regular expression match, if it does not match, the value is null, otherwise, gets the array that matches successfully. The non-global pattern gets an array of matching results, note that the first element is the first matching result, and the following element is a regular sub-match (regular content grouping match)varPattern =/\bjava\w*\b/; varText = "JavaScript is more fun than Java or javabeans!"; Result=pattern.exec (text)varPattern =/\b (Java) \w*\b/; varText = "JavaScript is more fun than Java or javabeans!"; Result=pattern.exec (text) The global schema needs to call the Exec method repeatedly, one to get the result until the match get result is null to get finishedvarPattern =/\bjava\w*\b/G; varText = "JavaScript is more fun than Java or javabeans!"; Result=pattern.exec (text)varPattern =/\b (Java) \w*\b/G; varText = "JavaScript is more fun than Java or javabeans!"; Result= Pattern.exec (text)
View Code
3. Related methods in string
Obj.search (regexp) gets the index position, searches the entire string, returns the first position where the match succeeded (the G mode is invalid) obj.match (regexp) gets the match, searches the entire string, gets the first match, If the regular is G mode find all Obj.replace (regexp, replacement) replace the match substitution, the regular has g to replace all, otherwise only replace the first match, $ 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 matched substring $$: Direct amount $ symbol
View Code
5. Time Processing
Time-related operations are available in JavaScript, and time operations are divided into two types of time:
- Time Unification Time
- local time (East 8 district)
For more operations see: http://www.shouce.ren/api/javascript/main.html
V. Statements and exceptions
1. Conditional statements
JavaScript supports two medium conditional statements, namely: if and switch
if (condition) { }Elseif(condition) { }else{ }
If statement
Switch (name) { case ' 1 ': = 123; Break ; Case ' 2 ': = 456; Break ; default : = 777; }
Switch
2. Circular statements
JavaScript supports three loop statements, namely:
var names = ["Alex", "Tony", "Rain"for (var i=0;i<names.length;i++) { Console.log (i); Console.log (Names[i]);}
Way One
var names = ["Alex", "Tony", "Rain"]; for (var in names) { console.log (index); Console.log (Names[index]);}
Mode two
while (condition) { // break ; // continue;}
Way Three
3. Exception Handling
try { //This piece of 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 is used to point to an Error object or other thrown object}finally {//Whether or not the code in the try is thrown (even if there is a return statement in the try code block), the finally code block is always executed. }
Note: Actively run out of exception throw Error (' xxxx ')
Vi. functions
1. Basic functions
The functions in JavaScript can basically be divided into three categories:
normal function func (ARG) { return true; } anonymous function var func = function (arg) { return "Tony"; } Self-executing functions (function (ARG) { console.log (ARG); }) (' 123 ')
Note: For function parameters in JavaScript, the number of actual arguments may be less than the number of formal parameters, and all actual parameters are encapsulated in the special value arguments within the function.
2. 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.
Remember that all scopes exist when the function is created and not executed.
function F2 () { var arg= 111; Function F3 () { console.log (ARG); } return f3;} ret = F2 (); ret ();
function F2 () { var arg= [11,22]; function F3 () { console.log (ARG); } = [44,55]; return f3; } = F2 (); RET ();
View Code
Note: The declaration is in advance and is made when the JavaScript engine is "precompiled."
MORE: http://www.cnblogs.com/wupeiqi/p/5649402.html
3. Closed Package
Closures are blocks of code that can contain variables that are free (not bound to specific objects).
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.
function F2 () { var arg= [11,22]; Function F3 () { return arg; } return f3;} ret = F2 (); ret ();
4. Object-oriented
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;} }
Reference Link: http://www.cnblogs.com/wupeiqi/articles/5602773.html
"Python Learning Path"--DAY16 (JavaScript)