Python automated shipping Koriyuki 22, JAVAScript

Source: Internet
Author: User
Tags closure define local local time serialization throw exception

First, Introduction

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. Learning HTML and CSS to make the page is just static Web page, if you need to have a variety of effects, then you need to learn a new language JavaScript and Dom to make the page programming dynamic.

Second, the Code storage location

Theoretically in the body and head can be, but the recommendation is placed at the bottom of the body code block, 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 see the page for a long time, if placed at the bottom of the body code block, So even if the JS code time is serious, it will not affect the user to see the page effect, but JS implementation of the special effect is slow.

JS code can be placed in a separate file, and then through the <script src= "Common.js" type= "Text/javascript" ></script> can import it in, or directly in the HTML file to write code directly, as shown below, two of the types can not write, because the browser default is JavaScript

Mode one: type= "Text/javascript" can be omitted
mode two: type= "Text/javascript" can omit <body> <script> js code content ..... </script></body>
Third, variable

The Declaration of variables in JavaScript is a very error-prone point,

Local variables: A local variable within a function must start with a Var, and if you do not use var within a function, you also define a local variable, so in order to not confuse, the local variable var begins, and the re-assignment also uses VAR

Global variables: The default representation of a global variable is declared outside the function.

 <script> name  = ' Seven '; //     no VAR, global variable  function        Func () { var  age = 18; //           plus var, local variable  age = 21; //         re-assign values to local variables, so define local variables or modify local variables plus var will not be a mess         var  age = 28;   Name  = "Tomcat"; //  re-assigns a value to a global variable       gender = "female";        This is a local variable, so don't mess it up, so define local variables using var 
alert (age); alert (name);
Alert (gender); } alert (name); Func () </script>

Code comments in javascript:

    • Single-line//
    • Multi-Line/* * *

Note: This comment takes effect only in the script block.

Iv. Types of data

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).
<SCRIPT>NUM1 = 123;    Define a digital num2 = new number (456);   Create a Digital object num3 = new number (789); Console.log (num1,num2,num3.valueof ());  Output 123 number {456} 789a = ' 888 '; Console.log (typeof a);   Output STRINGNUM4 = parseint (a);     Converts a string into a digital console.log (NUM4);      Output 888b = ' A123 '; num5 = parseint (b);   Unable to convert returns NaNconsole.log (NUM5);     Output nanif (IsNaN (NUM5)) {Console.log (' B cannot be converted to a number, so return nan ');    } Else{cosole.log (' B can be converted into numbers ');} Console.log (Isfinite (NUM1));  Determine whether it is a finite value, output Trueconsole.log (typeof num1);     Output what type, output NUMBERNUM6 = 12.888888;console.log (num6.tofixed (2));  Reserved decimal place, Output 12.89 Console.log (num6.toexponential (3));  12.89e+1 </script>
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 () 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                     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 value equals = =      = = = = = = = = = = = = = = = = = = = = = Equal     !==      or &&      and
<script>    console.log (1 = = ' 1 ');   //     console.log (1! = ' 1 ');   // false    Console.log (1 = = = ' 1 ');  // false    Console.log (1!== ' 1 ');  // true</script>
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
<script>Li= [11,22,33,44,55];        Console.log (li.length); Li.push (66);        Console.log (LI);        Li.pop ();        Console.log (LI); Li.unshift (0);        Console.log (LI);        Li.shift ();        Console.log (LI); L1= Li.slice (1,3);        Console.log (L1); Console.log (‘***************************************‘) Li.splice (1,0, ' first ');        Console.log (LI); Li.splice (2,1, ' second ');        Console.log (LI); Li.splice (2,2, ' second ');        Console.log (LI); Li.splice (2,1);        Console.log (LI); Console.log (‘***************************************‘) b= [' A ', ' B ', ' C '] Console.log (B.concat (LI)); Console.log (B.join (‘*‘));        Console.log (Li.reverse ()); Console.log ([4,2,1,5].sort ())</script>
Some examplesV. Other MISCELLANEOUS 1. Serialization
Json.stringify (obj)   # serialization, converting other types to string Json.parse (str)       # deserialization, converting an array dictionary of string types to the current type
    <script>        a = [11,22,33,44];        Console.log (typeof a);        Console.log (a);        ret = Json.stringify (a);        Console.log (typeof ret);        Console.log (ret);        Console.log (Json.parse (ret));    </script>
2. Escape
decodeURI () The escape character in the decodeuricomponent () URI component of the non-escaped character in the URL () encodeURI () URI            encodeuricomponent ()   escaping the characters in the URI Component Escape () to the               string Escape unescape ()             to the escaped string decoding Urierror                is thrown by the URL encoding and decoding method
    <script>        url = ' https://www.baidu.com/?name= betta ';        Console.log (encodeURI (URL));        Console.log (decodeURI (encodeURI (URL)));        Console.log (encodeuricomponent (URL));        Console.log (decodeuricomponent (encodeuricomponent (URL)));    </script>
3. Eval

Eval in JavaScript is a collection of eval and exec in Python that compiles code and can get return values.

Eval () Evalerror   the JavaScript code in the execution string
4. Regular Expressions

(1) Defining 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!"  = = = 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)    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) The global pattern    needs to call the Exec method repeatedly, one to get the result until the match get result is null to get the complete    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 strings  

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 replace all, otherwise only replace the first match,                                        $ number: matches the nth group content;                                          $& : The contents of the current match;                                          $ ': text located to the left of the matched substring;                                          $ ': text on the right side of the matched substring                                          $$: Direct Amount $ symbol
5. 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 (); Now.getmonth (  ); 6, month, note the month range is 0~11,6 represents July now.getdate ();   7, indicating no. 7th Now.getday ();    3, which represents Wednesday now.gethours ();  19, 24-hour system now.getminutes (); 49, Min Now.gettime ();   1435146562875, timestamp in number form

For more operations see:

Vi. Statements and exceptions

JavaScript supports two medium conditional statements, namely: if and switch

if (condition) {     }Elseif(condition) {             }else{     }
Switch (name) {    case ' 1 ':        = 123;           Break ;      Case ' 2 ':        = 456;          Break ;     default  :         = 777;}

2. Circular statements

JavaScript supports three loop statements, namely:

Way One: var names = ["Alex", "Tony", "Rain"for (var i=0;i<names.length;i++) {    Console.log (i);    Console.log (Names[i]);} Way two:var names = ["Alex", "Tony", "Rain"];  for (var in names) {    console.log (index);    Console.log (Names[index]);} Mode three:while(condition) {    // break ;    // continue;}

Note: Index is indexed, not content

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. }
Vii. function 1, function type

JavaScript functions basically can be divided into three classes, ordinary functions, anonymous functions, self-executing functions, in addition to note that for JavaScript function parameters, the number of actual parameters may be less than the number of formal parameters, All the actual parameters are encapsulated in the special value arguments within the function.

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.

(1) "No block-level scope in JavaScript"
function Main () {    if (1==1) {        var name = ' seven ';    }    Console.log (name);} Output: Seven

Add: The title adds double quotes because the LET keyword is introduced in JavaScript6 to specify that the variable belongs to a block-level scope.

(2) JavaScript takes function scope

In JavaScript each function acts as a scope, and the variables in the internal scope cannot be accessed externally.

function Main () {    var innervalue = ' Seven ';} Main (); Console.log (Innervalue); Error: Uncaught referenceerror:innervalue is not defined
(3) The scope chain of JavaScript

Because each function in JavaScript acts as a scope, the scope chain appears if function nesting functions occur.

XO = ' tomcat ';  function Func () {    var xo = "Seven";    function inner () {        var xo = ' Alvin ';        Console.log (XO);    }    Inner ();} Func ();

As shown above, there are three scopes of scope chain, if the scope chain, then the search for variables will appear in order, for the above example:

When executing Console.log (XO), its search order is based on the scope of the chain from the inside to the outside of the priority, if the inner layer does not step up to find, until the throw exception is not found.

(4) JavaScript is created before the scope chain is executed

The scope of JavaScript is created before it is executed, and it is only necessary to follow the scope chain to find out when to execute it later.

Example one:

XO = ' Tomcat '; function Func () {    var xo = "Seven";    function inner () {         console.log (XO);    }    return inner;} var ret = Func (); ret ();//output Result: Seven

The above code, before the function is called, the scope chain already exists:

    • Global scope, Func function scope, inner function scope

When executing "ret ();", because its surrogate refers to the inner function, the scope chain of this function has been defined before execution: global scope, Func function scope, and inner function scope, so, when executing "ret ();", The variable is searched based on the existing chain of scopes.

Example two:

XO = ' Tomcat '; function Func () {    var xo = "Mei";    function inner () {         console.log (XO);    }    XO = ' seven ';    return inner;} var ret = Func (); ret ();//output Result: Seven

The code above is the same as example one, and it also emphasizes that the scope chain already exists before the function is called:

    • Global scope, Func function scope, inner function scope

At different time, the value of the XO variable in the FUNC scope has been reset from "Eric" to "seven" when executing "var ret = Func ();", so you can only find "seven" when you Execute "ret ()".

Example three:

XO = ' tomcat '; function Bar () {    console.log (XO);} function Func () {    var xo = "Seven";         return Bar;} var ret = Func (); ret ();//output result: Tomcat

The code above has created two scope chains before the function is executed:

    • global scope, bar function scope
    • Global scope, Func function scope

When performing "ret ();", the RET surrogate refers to the bar function, and the bar function's scope chain already exists: global scope--bar function scope, so execution will be based on the existing scope chain to find.

(5) Declaring variables in advance

In JavaScript, if you do not create a variable and go directly to it, the error is:

Console.log (Xxoo);//Error: Uncaught Referenceerror:xxoo is not defined

If you create a value without assigning a value in JavaScript, the value is undefined, such as:

var xxoo;console.log (Xxoo);//output: undefined

Within the function, if you write this:

function Foo () {    console.log (XO);    var xo = ' Seven ';} Foo ();//output: undefined

The above code, not error, but output undefined, the reason is: the JavaScript function before it is executed, the variables are all declared, without assigning value. Therefore, the equivalent of the above example, the function in "precompiled" when the Var XO has been executed, so the above code output is undefined.

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 (' Tomcat '); var ret = obj. Func ("Python"); 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;}    }

Python automated shipping Koriyuki 22, 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.