JavaScript on the web front

Source: Internet
Author: User
Tags constant math local time natural logarithm root math throw exception

First, the existence form of JavaScript

Way One:

    alert (' Hello, World ');   </script>   ... </body>

Way two:

  ... </body>

About JS Storage location interpretation, first JS code can be placed in the HTML anywhere including head and body, but if JS loaded content is large and put in the head part, the body content can only wait until the JS loading complete to display, this will certainly affect the customer experience, Therefore, we recommend that you put the JS code block at the bottom of the body so that does not affect the loading speed to improve the experience. Here's a small example:

<Scriptsrc= "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 CodeSecond, JavaScript syntax

JavaScript and Java are similar to ";" The end of course can also be omitted here we choose not to omit, imagine a situation the server returns to the client is a large string that will be returned in a compressed form. If you do not add ";" HTML pages may encounter unresolved situations, so it is recommended that you add a semicolon ";", the following is the full format:

var t = "Hello,world";

Note that JavaScript is case-sensitive;

Third, JavaScriptNotes

JavaScript can be divided into single-line comments and multiline comments

// represents a single-line comment /* represents a multiline comment */
Iv. JavaScript variables

JavaScript can be divided into global variables and local variables, declaring variables if the keyword var is represented as a local variable, it should be noted that the variable name cannot be the same as the keyword such as: if while, etc.;

Name = "Tiny";    // Global Variables var // Local Variables
V. Types of data

The data types of JavaScript are: Number, String, Boolean (Boolean), Array, Object (objects), null (NULL), undefined (Undefined).

1. Digital

JavaScript is not divided into integers and floating-point numbers collectively known as number types;

// Integer 123 // floating point 0.456 // scientific notation means 1.2345x1000, equivalent to 1234.5 // Negative number // Nan means not a number, which is represented by Nan when the result cannot be evaluated // Infinity is infinitely large, and is represented as infinity when the value exceeds the maximum value that JavaScript can represent.

The numbers provide a method, which is commonly used for:

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

Method:

    number support for numbers Number.MAX_VALUE    maximum numeric number.min_value    minimum value Number.NaN    special non-numeric value number.negative_ INFINITY    Negative Infinity large number.positive_infinity    positive Infinity number.toexponential ()    format the digital number.tofixed with exponential notation ()    Use fixed-point notation to format the digital number.tolocalestring ()    to convert a number into a cost-formatted string number.toprecision () to    format a valid bit of a number number.tostring ()    converts a number to a string number.valueof ()    returns the original value
Methods of Numbers

More numerical calculations:

    the math arithmetic function and the constant Math.Abs () calculate the absolute value Math.acos () to calculate the    inverse cosine math.asin () to    calculate the sine chord value Math.atan ()    Calculates the inverse tangent value math.atan2 ()    calculates the angle from the x-axis to a point Math.ceil ()    computes a number on the rounding Math.Cos ()    calculates the cosine value MATH.E the    arithmetic constant Emath.exp ()    computes Exmath.floor ()    to a number of rounding math.ln10    arithmetic constant LOGE10MATH.LN2    arithmetic Constants Loge2Math.log ()    Calculates the natural logarithm of a number math.log10e    arithmetic constant log10emath.log2e    arithmetic constant Log2emath.max ()    returns the maximum parameter Math.min ()    Returns the smallest parameter Math.PI    arithmetic constant Pimath.pow ()    calculates xymath.random ()    returns a pseudo-random number math.round ()    rounded to the nearest integer Math.sin ()    calculates the sine value math.sqrt ()    calculates the square    root math.sqrt1_21/figs/squroot.gifMath.SQRT2    arithmetic constant figs/ Squroot.gifMath.tan ()    calculates the tangent value
the Math method

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.

var answer= "It ' s Alright"var answer= "He is called ' Johnny '"var answer= ' He is called "Johnny";

Common features of strings:

Obj.length length Obj.trim () remove blank obj.trimleft () obj.trimright) Obj.charat (n)               Returns the nth character in a string Obj.concat (value, ...) StitchingObj.indexof (Substring,start)Sub-sequence position Obj.lastindexof (Substring,start) sub-sequence position obj.substring (from, to) gets sub-sequence from indexObj.slice (Start, end)Slice obj.tolowercase () uppercase obj.touppercase () lowercaseobj.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)Replace, there is g in the regular replaces all, otherwise only the first match, $ number: matches the nth group content; $&: When                                     The contents of the previous match; $ ': Text to the left of the matched substring; $ ': Text on the right side of the matching substring $$: Direct Volume $ symbol

It is important to note that JavaScript match substitution supports regular expressions such as:

<script>       = "Asdfa5qwerq7uyy";         = A.replace (/(\d+)/, "$&x");        Console.log (c); </script>

The meaning of this sentence is to match the first number by matching the value matched to the value x, "$&" represents the current match to the content, Console.log for the printed result;

3, 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

The list in JavaScript and Python is similar;

Common functions:

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) to specify the position of the replacement element                    Obj.splice (n,1)     Specify location Delete element Obj.slice ()        slice obj.reverse ()      invert obj.join (Sep)       Concatenate array elements to construct a string Obj.concat (Val,..)  Concatenate array obj.sort ()         to sort the elements of a group

5,undefined and Null

Undefined This value indicates that the variable does not contain a value. You can empty a variable by setting the value of the variable to null.

Cars=null;person=null;

6. Objects

JavaScript objects are like dictionaries in Python, and objects are separated by curly braces. Inside the parentheses, the properties of the object are defined in the form of name and value pairs (name:value). Attributes are separated by commas:

var person={firstname: "John", LastName: "Doe", id:5566};

The object (person) in the example above has three attributes: FirstName, LastName, and ID.

Spaces and lines do not matter. Declarations can span multiple lines:

var person="John", LastName  "Doe", id        :  5566 };

Instance:

7. Declaring variable types

When declaring a new variable, the keyword "new" can be used to declare its type:

var carname=new  String; var x=      new number ; var y=      new  Boolean; var cars=   new  Array; var New Object;
Vi. 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

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

Note: When you define a regular expression, "G", "I", "M" represent global matches, ignoring case and multiline matching.

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

Vii. Statements and exceptions

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 Statement

1. Circular statements

JavaScript supports three loop statements, namely:

var names = ["Alex", "Tony", "Rain"];  for (var in names) {    console.log (index);    Console.log (Names[index]);
Loop Statement One
var names = ["Alex", "Tony", "Rain"for (var i=0;i<names.length;i++) {    Console.log (i);    Console.log (Names[i]);
Looping Statements Two
 while (condition) {    // break ;    // continue;}
Loop Statement three

2. Exception handling

Javascripty exception handling is similar to Python;

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: Throw exception throw error (' xxxx ')

Viii. 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."

3. Scope

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 ();

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;    

  

JavaScript for the web front end

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.