Step Python3 (11)--2--web JavaScript

Source: Internet
Author: User
Tags local time throw exception

JavascripJavaScript is a programming language, and the browser has a JavaScript interpreter in it, so the browser can interpret and handle the code after it is written in the JavaScript language rules. First, how to write

1. JavaScript code exists in form

<! - -  方式一  - - > <script  type=" text/javascript"  src = "JS文件" >< / script> <! - -  方式二  - - > <script  type= "text/javascript" >      Js代码内容 < / script>  

2, JavaScript code storage location

(1) in the head of HTML

(2) 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.

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.

<script type = "text/javascript" >      / / 全局变量      name = ‘seven‘ ;      function func(){          / / 局部变量          var age = 18 ;          / / 全局变量          gender = "男"      } < / script>

Code comments in javascript:

    • Single-line//
    • Multi-Line/* * *
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
      • Array
      • Dictionary
      • ...

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.

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).

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,
However, JavaScript does not provide a way to modify the contents of a known string.
Common features:
Obj.length 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 a subsequence from an 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 (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:
The size of the obj.length array
Obj.push (ele) trailing append element
Obj.pop () tail Gets an element
Obj.unshift (ele) head insertion element
Obj.shift () Removing elements from the head
Obj.splice (Start, DeleteCount, value, ...) inserting, deleting, or replacing elements of an array
Obj.splice (n,0,val) specify position insert element
Obj.splice (n,1,val) specifying position substitution elements
Obj.splice (n,1) specify location Delete element
Obj.slice () slices
Obj.reverse () reversal
Obj.join (Sep) joins the array elements to construct a string.
Obj.concat (val,..) connection array
Obj.sort () sorting an array element

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, defining a regular expression
/.../to define a regular expression
/.../g for global matching
/.../i for case-insensitive
/.../m for multiline matching
JS regular match is itself support for multiple lines, The multiline match here only affects the regular expression ^ and the $,m pattern will also use ^$ to match the contents of the newline)
Eg:
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 a regular expression can also reg= the new REGEXP ()

Regular expressions are supported in

2, match
JavaScript, which provides two main features:
(1) test (string) check for and regular matches in string
N = ' uui99sdf '
Reg =/\d+/
Reg.test (n)---> True

# matches as long as the regular is present in the string, if you want to match the beginning and end, you need to add ^ and $
(2) Exec (string) to get the contents of the regular expression match before and after the regular expressions, if they do not match, The value is null, otherwise a successful array is obtained. The
gets the contents of the regular expression match, if it does not match, the value is null, otherwise, gets the array that matches successfully.

Non-global mode
Gets an array of matching results, note that the first element is the first matching result, followed by a regular sub-match (regular content grouping match)
var pattern =/\bjava\w*\b/;
var text = " JavaScript is more fun than Java or javabeans! ";
result = pattern.exec (text)

var pattern =/\b (Java) \w*\b/;
var text = "JavaScript is more fun than Java or javabeans! ";
result = pattern.exec (text)

Global mode
needs to call the Exec method repeatedly to get the result one at a-until the match get result is null to get finished
var pattern =/\bjava\ w*\b/g;
var text = "JavaScript is more fun than Java or javabeans!";
result = pattern.exec (text)

var pattern =/\b (Java) \w*\b/g;
var text = "JavaScript is more fun than Java or javabeans! ";
result = pattern.exec (text)

3. Related methods in string
Obj.search (regexp) Gets the index position, searches the entire string, returns the first position where the match succeeded (invalid G mode)
Obj.match (regexp) Gets the match, searches the entire string, gets the first match found, and if the regular is G mode finds all
Obj.replace (regexp, replacement) replaces the match substitution, 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

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) {}
else if (condition) {}
else{}

Switch (name) {
Case ' 1 ':
Age = 123;
Break
Case ' 2 ':
age = 456;
Break
Default:
Age = 777;
}
2. Circular statements

JavaScript supports three loop statements, namely:
(1)
var names = ["Alex", "Tony", "Rain"];

for (Var i=0;i<names.length;i++) {
Console.log (i);
Console.log (Names[i]);
}
(2)
var names = ["Alex", "Tony", "Rain"];

For (var index in names) {
Console.log (index);
Console.log (Names[index]);
}
Note: This loop gets the subscript, not the value of the array.
(3)
while (condition) {
break;//continue;
}
3. Exception Handling

try {
This code runs from top to bottom, where any one of the statements throws an exception and 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 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: Throw exception throw new Error (' xxxx ')

Vi. Functions and scopes

1. Basic functions
The functions in JavaScript can basically be divided into three categories:
Common functions
function func (ARG) {
return true;
}

anonymous functions
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, the special values within the function
All the actual parameters are encapsulated in the arguments.
2. Scope
Each function in JavaScript has its own scope, and when a function is nested, a scope chain appears. When a variable is used by the inner layer function,
A loop that is based on the scope chain from the inner to the outer layer, or the exception if it does not exist.
MORE: http://www.cnblogs.com/wupeiqi/p/5649402.html
3. Closed Package

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 ', 18);
var ret = obj. Func ("SB");
Console.log (ret);
You need to be aware of the above code:
(1) Foo functions as a constructor
(2) This refers to the object
(3) 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;
}
}



Step Python3 (11)--2--web JavaScript

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.