Python Basics-11th article -11.1javascript Basics

Source: Internet
Author: User
Tags closure constant math local time mathematical functions natural logarithm set set hasownproperty

    • JavaScript is an interpretive programming language, mainly to enhance the dynamic effect of HTML pages
    • JavaScript is made up of three parts: ECMAScript, BOM, DOM
    • Single-line comment//multi-line/* */

Introduce the way to introduce external files
<script type= "Text/javascript" src= "JS file" ></script>
    • In addition to being introduced as a file, it is written in HTML
    • The recommendation is written at the bottom of the body, so that the page can be presented to the user as soon as possible, reducing the waiting time for the visitors

Variable
    • In JavaScript, local variables must be declared with VAR, or global if no var is written.
    <script type= "Text/javascript" >/        /global variable        name = Alex        function func () {        //local variable var age        = 18                //global variable        gender = "Women"        }    </script>

Operator 1, arithmetic operators
    • + addition (if a unary operation, and a non-numeric value, the number () transformation function is called to convert the value)
    • -Subtract (convert unary to negative)
    • + + increments by 1 (by number (), plus 1 to the operand)
    • --Decrement 1
    • * Multiplication
    • /Division
    • % modulus

2. Comparison operators
    • = = = with! = = Strict operator, the comparison process does not have any type conversions
    • = = with! = If two operation values are not the same type, some types of conversions are attempted before comparison
    • > and < greater than and less than
    • >= and <= greater than or equal to or less than

3. Logical operators
    • ! Non (returns a Boolean value)
    • && and
    • || Or
1> Replace if statement//before the condition is established run the following operation (a = = b) && dosomething ();2> for the callback function//If the parameter A is not passed a value, a defaults to the undefined false value, so a () is not executed. function fn (a) {    a && a ();}

Data type
    • Null represents an empty object pointer, commonly used to describe null values;
    • Undefined indicates that the variable is not defined

1. Digital
    • parseint () Converts a value to an integer, or Nan if unsuccessful
    • Parsefloat () Converts a value to a floating-point number, or Nan if unsuccessful
    • NaN is not a number, you can use isNaN (num) to determine
    • Infinity Infinity, you can use Isfinite (num) to determine

2. String

3. Boolean type
    • True (True) and False (false)

4. Arrays
var name = Array ("Nick", "Alex"); var name = ["Nick", "Alex"]

5. Math
    • The Math object is a static object, not a constructor, in fact, math is just a JavaScript-set object namespace for storing mathematical functions that perform normal arithmetic tasks
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. 
View Code

Statement 1, conditional statements
    • If statement
if (condition) {                }else if (condition) {                }else{                }
    • Switch statement
    Switch statement, name equals Alex executes the first case, equals Nick executes the second case, and the other executes the default    switch (name) {case        "Alex": Age            =;            break;        Case "Nick": Age            = +;            break;        Default: Age            = 0    }

2. Circular statements
    • For loop
        var names = ["Alex", "Nick"];        for (Var i=0;i<names.length;i++) {            console.log (i);            Console.log (Names[i]);        }
    • For In loop
        var names = ["Alex", "Nick"];        For (var index in names) {            console.log (index);            Console.log (Names[index]);        }
    • While loop
        while (condition) {            //break;            //continue;        }
    • Do-while Cycle
        The loop code executes at least once, resulting in a 1        var num = 0;        do{        num++;        } while (NUM>10);

3. Label statement
    • The label statement can be interpreted as jumping out of any loop

4. Exception Handling
    • Actively throws exception throw Error (' xxx ')
        try{            //This code runs from top to bottom, where any one of the statements throws an exception the code block ends run        }        catch (e) {            ///If an exception is run out of the try 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{            //No matter how the above code, finally code block will always execute        }

Functional function
    • Three ways to define a function
        normal function        func (ARG) {            return true;        }        anonymous function        var func = function (arg) {            return "Nick";        }        Self-executing functions        (function (ARG) {            console.log (ARG);        }) ("Nick")
    • Function parameter: The number of function parameters can be less than the number of actual required parameters, the default is undefined, the parameter pass-by default does not work
    Function Man (name,age) {        console.log (name,age);    }    Man ("Nick", 18); Nick    ("Nick");  Nick undefined man    ("Nick", 18,19);//Nick 18
    • Arguments can accept all parameters, returning an array
    Function Man () {        console.log (arguments);    }    Man ("Nick", 18); ["Nick",] man    ("Nick");  ["Nick"] man    ("Nick", 18,19);//["Nick", 18,19]

Scope and scope chain of functions
    • There is no block-level scope in JavaScript
var name = "Nick";        (function Main () {            console.log (name);//undefined            if (1) {                var name = "Alex";            }            Console.log (name);//alex        }) ();        Console.log (name);//nick        //declaration should be made in advance, when the JavaScript engine "precompiled", the function will be executed, the variables are all declared in the river, without assigning a value
    • Scope Chain: Each constructor has an internal object pointer to the prototype object, and the prototype object also contains a pointer to the constructor, so that layers are progressive, forming a scope chain
      var name = "Nick";        function Main () {            function F1 () {                var name = "Alex";                Console.log (name);            }            function F2 () {                console.log (name);//nick            }            F1 ();            F2 ();        }        Main ();        Find the scope chain for//F2 () from the inside to outside priority        F2 ()--"Main ()

Closed Package
    • A closure is a function that can read other variables inside a function
    Function F1 () {        var n = 1;        Add = function () {            n++;        }        function F2 () {            console.log (n);        }        return f2;    }    var result = F1 ();    Result ();//1    Add ();    Result ();//2

Closures so that the function of the variables are stored in memory, memory consumption is large, so less closure, otherwise it will cause the performance of the Web page is low, in IE may lead to the disclosure of memory, before exiting the function, the unused local variables are all deleted

Object-oriented three major features
    • Encapsulation: Hide the details of the implementation of the Code and implement the modularity of the Code
    • Continue: Extend code modules that already exist to implement code reuse
    • Polymorphism: Different implementations of interfaces to enable interface reuse
Keywords
    • This refers to the object at this time
    • The new object must be created using the

Constructor mode: However, the same function is encapsulated in different objects, resulting in a waste of memory

    function Foo (name,age) {this        . name = name;        This. Age = age;        This. Func = function () {            return this. Name + this. Age        }    var obj = new Foo ("Nick");    var ret = obj. Func ();    Console.log (ret);    var obj2 = new Foo ("Alex", 22);

Prototype mode

    function Foo (name,age) {        this.name = name;        This.age = age;    }    Foo.prototype = {        getinfo:function () {            var str = "is good";            return this.name + str;        }        Func:function () {            return this.name + this.age;        }    }    var obj = new Foo ("Alex", +);    Console.log (obj.name);//alex    Console.log (obj.age);//22    var ret = obj. GetInfo ();    Console.log (ret);//alex is good    var ret2 = obj. Func ();    Console.log (Ret2);//alex18

all Constructors ' prototype properties point to another object (the same piece of memory address), and all properties and methods of the object are inherited by the instance of the constructor.

verification method of prototype mode
    • isPrototypeOf () is used to determine whether an object exists in the prototype chain of another object
    Foo.prototype.isPrototypeOf (obj)  //true    Foo.prototype.isPrototypeOf (obj2)  //true
    • hasOwnProperty () is used to determine whether an object (not including the prototype chain) has an execution property
    Obj.hasownproperty ("name")  //true    obj.hasownproperty ("Age")  //true
    • The In operator determines whether an instance has a property
    ' Name ' in obj  //true    ' age ' in obj  //true

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 can either run code or get return values

    A = eval ("+ +");    Console.log (a);
4. Regular expressions
    var p =/nick/g;    Console.log (P.test ("Nickalexnick")),//true    Console.log (p.exec ("Nickalexnick")),//["Nick", Index:8,input: " Nickalexnick "]

regular expressions are supported in JavaScript, which provides two main features:

    • Test (string) to detect if a regular match
    • EXEC (string) to get the contents of a regular match

Matching mode:

    • g: Represents a global pattern that matches all strings and stops when the first item is not matched
    • i: Indicates case insensitive (case-insensitive) mode
    • m: Represents multiline mode, and when the end of a line of text is reached, it continues to look for matching items in the next line
the meta         -character name              matches the object.             Single arbitrary character              (except carriage return \ r, newline \ n, line delimiter \u2028, and Segment delimiter \u2029) [] a single arbitrary character            that is             listed by the [] character group [^]           exclusion character Group        is not listed as a single character ?             Question mark               matches 0 or 1 times *              asterisk               matches 0 intersection or multiple +              plus               matches 1 or more {Min,max}     interval quantifiers           Matches at least Min, max times ^              caret             line start position $             USD             line end position |              The vertical bar               separates any one of the expressions () brackets to limit the range of the               multi-select structure, the elements that annotate the quantifiers, and the capture text for the inverse reference \1,\2 ...      The reverse reference            matches the first, second ... Text that matches an expression within a group of parentheses
Meta character
\d     number, equivalent to [0-9]\d     non-numeric, equivalent to [^0-9]\s     whitespace character \s     non-whitespace character \w     letter, number, underscore, equivalent to [0-9a-za- Z_] (Chinese characters do not belong to \w) \w     non-letters, numbers, underscores, equivalent to [^0-9a-za-z_]
View Code

5. Time Processing

  There are two kinds of times in the time operation:

    • Unified Time
    • local time (East eight district)
Date and Time Object Date.getdate () returns the day of the one month Date.getday () returns the day of the Week Date.getfullyear () returns the year field of the Date object Date.get Hours () Returns the hour field of the Date Object Date.getmilliseconds () returns the millisecond field of the Date Object Date.getminutes () returns the minute field of the Date Object Date.getmonth () returns The month field of the Date Object Date.getseconds () returns the second field of the Date Object Date.gettime () returns the millisecond of the Date object Date.gettimezoneoffset () determines the time difference from GMT date.g    Etutcdate () Returns the day that is one months (world time) Date.getutcday () returns the day of the Week (World Time) Date.getutcfullyear () returns year (World time) date.getutchours () Returns the hour field (world time) of a Date object Date.getutcmilliseconds () returns the millisecond field of a Date object (World time) Date.getutcminutes () returns the minute field of a Date object (World time) Date.getut    Cmonth () returns the month of the Date object (World time) Date.getutcseconds () returns the Date object's second field (World Time) Date.getyear () returns the Date object's Year field (World Time) Date.parse () Parse Date/The time string date.setdate () sets a day for one months Date.setfullyear () sets the year, or you can set the month and Day Date.sethours () to set the Hour field, minute field, second field, and millisecond field date for the Date object. Setmilliseconds () Sets the millisecond field of the Date Object Date.setminutes () sets the minute and second fields of the Date Object Date.setmonth () Sets the month field and the day field of the Date object date.setsec Onds () sets the second and millisecond fields of the Date Object Date.settime () sets the Date Object Date.setutcdate () in milliseconds setting a day in one months (world time) date.setutcfullyear () set Set year, month, and Day (World Time) date.setutchours () Sets the hour field, minute field, second field, and millisecond field (world time) of the Date Object Date.setutcmilliseconds () sets the millisecond field of the Date object (World time) date . setUTCMinutes () Sets the minute field and the second field (world time) of the Date Object Date.setutcmonth () sets the Date object's month field and day number fields (World time) Date.setutcseconds () to set the Date object The seconds field and the Millisecond field (at the time of the World) Date.setyear () sets the Date object's Year field date.todatestring () to return dates as a string date.togmtstring () to convert date to world time words    Character string date.tolocaledatestring () returns the date part of a Date object as a locally formatted string date.tolocalestring ()    Converts a date to a locally formatted string date.tolocaletimestring () returns the time portion of a Date object as a locally formatted string date.tostring () Converts date to string date.totimestring () returns the Date object as a string, date.toutcstring () converts date to a string (World time) date. UTC () Converts the date specification to milliseconds date.valueof () converts date to milliseconds
View Code

See: http://www.cnblogs.com/suoning/p/5656403.html

Python Basics-11th article -11.1javascript Basics

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.