JavaScript from getting started to forgetting

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

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
    • Second, the variable
    • Third, the data type
        • 1. Numbers (number)
        • 2. Strings (String)
        • 3. Boolean Type (Boolean)
        • 4. Arrays (Array)
        • 5. Dictionary (Object)
    • Iv. Other
        • 1. Serialization
        • 2. Escape
        • 3. Eval
        • 4. Regular expressions
        • 5. Time Processing
    • V. Statements and exceptions
    • Vi. functions
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

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

<script src="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>
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, which take effect only in the script block:
Single-line//
Multi-Line/* * *

The code in JavaScript ends with a semicolon.

Use Chrome to review elements for troubleshooting.

Third, the data type

The data types in JavaScript are divided into primitive types and object types:
Primitive type: Numeric, String, Boolean --immutable immutable
Object type: Array, "dictionary", ...

NULL, undefined-non-modifiable non-changeable
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). true-> Non-digital
Infinity, infinitely large. Can be judged using isfinite (num). true-> finite number

Other numerical calculations:

Math.LN1010的自然对数。Math.LOG10E以10为底的e的对数。Math.PI常量piMath.SQRT22的平方根。静态函数Math.abs( )计算绝对值Math.ceil( )对一个数上舍入Math.floor( )对一个数下舍入Math.cos( )计算余弦值Math.exp( )计算e的指数Math.log( )计算自然对数

Determines ret = typeof a the type, returning a string, such as ' number '.

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 the Obj.indexof (Substring,start) sub-sequence position, looking for the Obj.lastindexof (Substring,start) sub-sequence position, from the back to the obj.substring (from, to)                    Get sub-sequence Obj.slice (start, end) slice obj.tolowercase () uppercase Obj.touppercase () based on index Lowercase supports regular/\d+/->/regular expression content/, supports grouping/(/\d+) e/obj.split (delimiter, limit) segmentation, and limit means taking several matching values. Obj.search (regexp) matches from the beginning, returning the first position where the match succeeded (G invalid) Obj.match (regexp) global search, with G representing the global search, or only the first one is found. Match (/e/g) obj.replace (regexp, replacement) is replaced, there is g in the regular replaces all, otherwise only the first match is replaced by $ number: matches in the nth group                                     Repalce (/(\d+) \w+ (\d+)/g, "$2$1") $&: Refers to the content of a successful match; Repalce (/(/\d+)/g, "$&" + "X") $ ': text located to the left of the matched substring;: The text $$ to the right of the matched substring: the direct amount $ symbol, where $ is the transfer character 
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 (Array)

The arrays in JavaScript are similar to those in Python, and can be understood as arrays formed by linked lists, unlike arrays formed by contiguous memory spaces in Java, C #.

Common features:

obj.length          数组的大小 obj.push(ele)       尾部追加元素obj.pop()           尾部获取一个元素obj.unshift(ele)    头部插入元素obj.shift()         头部移除元素obj.splice(start, deleteCount, value, ...)  插入、删除或替换数组的元素obj.splice(n,0,val) 指定位置插入元素obj.splice(n,1,val) 指定位置替换元素obj.splice(n,1)     指定位置删除元素obj.slice( )        切片obj.reverse( )      反转obj.join(sep)       将数组元素连接起来以构建一个字符串obj.concat(val,..)  连接数组obj.sort( )         对数组元素进行排序
5. Dictionary (Object)

A dictionary made from objects, type object.

> a = {k1:123,k2:456}> a['k1']< 123
Iv. other 1, serialization
JSON.stringify(obj)   序列化JSON.parse(str)       反序列化
2. Escape
decodeURI( )                     解码 URl中未转义的字符decodeURIComponent( )            URI组件中的未转义字符encodeURI( )                     编码 URI中的转义字符encodeURIComponent( )            编码URI组件中的字符,包括://什么的escape( )                        对字符串转义unescape( )                      给转义字符串解码URIError                         由URl的编码和解码方法抛出
3. Eval

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

eval(“1+1”) eval(“a=1”) eval(‘for(var i=1;i<10;i++){console.log(i)}’)

Evalerror executing JavaScript code in a string

4. Regular expressions

1. Define Regular expressions

/.../  用于定义正则表达式/.../g 表示全局匹配/.../i 表示不区分大小写/.../m 表示多行匹配JS正则匹配时本身就是支持多行,此处多行匹配只是影响正则表达式^和$,m模式也会使用^$来匹配换行的内容

Note: Defining regular expressions can also reg= new RegExp ()

2. Matching

Regular expressions are supported in JavaScript, which provides two main features:
1, test (string) checks whether the string matches the regular, with many

n = 'uui99sdf'reg = /\d+/reg.test(n)  ---> true只要正则在字符串中存在就匹配,如果想要开头和结尾匹配的话,就需要在正则前后加 ^和$

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

获取正则表达式匹配的内容,如果未匹配,值为null,否则,获取匹配成功的数组。 非全局模式    获取匹配结果数组,注意:第一个元素是第一个匹配的结果,后面元素是正则子匹配(正则内容分组匹配)    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) 全局模式    需要反复调用exec方法,来一个一个获取结果,直到匹配获取结果为null表示获取完毕    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)
5. Time Processing

Time-related operations are available in JavaScript, and time operations are divided into two types of time:

Time Unified Time Date.setutcdate
local time (East 8 district) date.setdate

V. Statements and exceptions

1. Conditional statements

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

   if(条件){     }else if(条件){             }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:

var names = ["alex", "tony", "rain"]; for(var i=0;i<names.length;i++){    console.log(i);    console.log(names[i]);}
//foreach循环names = ["alex", "tony", "rain"];dic = {"k1":123, "k2":456};//不同于python,这里循环的是index不是itemfor(var index in names){    console.log(index);    console.log(names[index]);}for(var key in dic){    console.log(key)}
while(条件){    // break;    // continue;}

3. Exception Handling

try {    //这段代码从上往下运行,其中任何一个语句抛出异常该代码块就结束运行}catch (e) {    // 如果try代码块中抛出了异常,catch代码块中的代码就会被执行。    //e是一个局部变量,用来指向Error对象或者其他抛出的对象}finally {     //无论try中代码是否有异常抛出(甚至是try代码块中有return语句),finally代码块中始终会被执行。}

Note: Throw exception throw error (' xxxx ')

Vi. functions

1. Basic functions

The functions in JavaScript can basically be divided into three categories:

// 普通函数function func(arg){   return true;}     // 匿名函数var func = function(arg){   return "tony";}  // 自执行函数,定义一个函数自己执行自己f1(arg){    console.log(arg);}f1('123')//等价于(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. All actual parameters are encapsulated in the arguments array of special values within the function.

function f1(a,b,c){    console.log(arguments)    console.log(a,b,c)}f1(1,2)>> [1,2]>> 1 2 undefined

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.

var arg =000;function f1(){    var arg= 111;    function f2(){        console.log(arg);    }    f2();}f1();>> 111
var arg =000;function f1(){    var arg= 111;    function f2(){        console.log(arg);    }         return f2;} ret = f1(); //f2ret();  //执行f2>> 111  //拿出f2也没用,作用域不变

Declared ahead of time, when the JavaScript engine is "precompiled".

//预编译从上到下全部变量进行声明 不赋值function f1(){    console.log(name);}f1();>> 报错function f1(){    //var name;    console.log(name);    var name = 'momo';}f1();>> undefined

3. Closed Package

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

No class, only functions

//this == self//like __init__ 构造方法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:

    • 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;    }}//或者 推荐Foo.prototype.GetInfo = function(){return this.Name + this.Age},Foo.prototype.Func = function(arg){return this.Name + arg;}

?

JavaScript from getting started to forgetting

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.