The path of Python 54-javascript

Source: Internet
Author: User
Tags closure local time

Directory

First, how to write

Second, the variable

Third, the data type

Iv. Other

V. Statements and exceptions

Vi. functions

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 (type= "Text/javascript" can be written without writing)

<!--way one--><script type= "Text/javascript" src= "js file" ></script><!--mode two--><script type= " Text/javascript ">JS Code content </script>


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, then even if the JS code is time consuming, it will not affect the user to see the page effect.


3. Notes

Single-line comment//

Multiline Comment/* */


4. Commissioning

Writing debugging in HTML

Temporary can be in the browser's terminal review element-console

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" >//global variable name = "Seven"; function func () {//local variable var age = 18;//global variable gender = "male";} </script>

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 is a keyword in the JavaScript language that represents a special value that is commonly used to describe a "null value"

Undefined is a special value that indicates that the variable is undefined


1. Digital

Integer and floating-point values are not distinguished in JavaScript, 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. You can use isNaN (num) to determine

Infinity, infinitely large. You can use Isfinite (num) to determine

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


Common features:

Obj.length length Obj.trim () Remove white space 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 the sub-sequence Obj.slice (start,end) slice obj.tolowercase () uppercase obj.touppercase () lowercase obj.split (delimiter,limit) Split Obj.search ( regexp) match from scratch, return the first position (G invalid) Obj.match (regexp) Global Search, if there is a G in the regular to find all, otherwise only find the first obj.replace (regexp,replacement) Replacement, G in regular replaces index, otherwise only first match $ number: matched nth group content $&: Content currently matched $ ': text on the left side of the matched substring $ ': Text $$: Direct amount $ symbol


3. Boolean type

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 () appends the trailing element Obj.pop () to the tail of an element obj.unshift () to the head of the insertion element Obj.shift () The head removes the 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) The specified position to delete the element Obj.slice () Slice Obj.reverse () invert obj.join () joins the array elements to build 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. Escaping

decodeURI ()characters that are not escaped from the URI

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 regular expressions

/.../ for defining regular expressions

/.../g represents a global match

/.../i indicates case insensitive

/.../m for multi-line matching

JS regular match itself is to support multiple lines, where multiple lines match just affect the regular expression ^ and $,m mode will also use ^$ to match the contents of the line wrap

var pattern =/^java\w*/gm;var Text = "JavaScript is more fun than \njavaee or javabeans!"; result = Pattern.exec (text);

Note: Defining a regular expression can also be Reg = new RegExp ()


(2) Matching

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

Test (String) checks if the string matches the regular match n = "uui99sdf" reg =/\d+/reg.test (n)

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 not matched, 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, 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)


Global mode

You need to call the Exec method again and again to get the result one at a-until the match gets the result null indicates that the fetch is 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 (invalid G mode) Obj.match (regexp)                       get matches, search the entire string, Gets the first match found, if the regular is G mode find all Obj.replace (regexp, replacement)       replace match Replace, the regular has g to replace all, Otherwise, only the first match is replaced                                        $ Number: Matches the nth group content;                                       $&: Current matching content;                                       $ ': Text on the left side 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. Looping 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]);}    var names = ["Alex", "Tony", "Rain"];for (var index in names) {Console.log (index); Console.log (Names[index]);}    while (condition) {//break; Continue;}


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 the code in the try code has an exception thrown (even if there is a return statement in the try 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: All scopes already 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);} arg = [44,55];return f3;} ret = F2 (); ret ();

Note: The declaration is in advance and is made when the JavaScript engine is "precompiled."

MORE: http://www.cnblogs.com/wupeiqi/p/5649402.html


Five words:

No block-level scope in JavaScript (supplemental: the title adds double quotes because the LET keyword is introduced in JavaScript6 to specify that the variable belongs to the block-level scope)

JavaScript takes a function scope, and in JavaScript each function acts as a scope, outside of which the variables in the inner scope cannot be accessed

The scope chain of JavaScript, because each function in JavaScript acts as a scope, the scope chain appears if a function nesting function occurs.

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

Declaration in advance

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

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

The JavaScript function will declare all the variables in it before it is executed, without assigning a value


3. Closures

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. Closures, obtaining 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; }}


This article is from the "Eight Miles" blog, so be sure to keep this source http://5921271.blog.51cto.com/5911271/1923821

The path of Python 54-javascript

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.