[Javascript advanced programming] excerpt 2 Chapter 5 reference type, Chapter 5 javascript

Source: Internet
Author: User
Tags date1 vars

[Javascript advanced programming] excerpt 2 Chapter 5 reference type, Chapter 5 javascript
Chapter 5 reference types

1. There are two ways to create an Object:

The first is to use the new operator: varperson = new Object ();

The second method is to use the literal representation of the object: var person = {name: 'test'}; (note that the last attribute is not followed by a comma, otherwise, an error may occur in some browsers.) When using a literal to create an object, the attribute name can also use a string: var person = {"name": "test "};

2. You can use the dot notation or square brackets notation to access the attributes of an object during object attribute access:

var person = {“name”:”test”};alert(person.name);alert(person[“name”]);

There is no big difference between the two methods, but the square brackets syntax can be used to access attributes through variables.

1. Array type:

var arr1 = new Array();var arr2 = Array(1, 2, 3);var arr3 = [];

2. Stack method:

ECMAScript provides a way to make arrays behave like other data structures, such as stacks and queues.

 var stack = []; for( var i = 0; i< 10; i++ ){     stack.push(i ); } console.log( stack.join("-") ); for( var i = 0; i < 5; i++ ){     console.log("pop: " + stack.pop() );  }

3. Queue method:

The queue method adds items at the end of the queue, and removes items at the front end of the queue.

var queue = [];for( var i = 0; i < 10; i++ ){   queue.push( i );}console.log( queue.join("-") );for( var i = 0; i < 5; i++ ){   console.log( "shift: " + queue.shift() );}

Unshift is opposite to shift. It can add any number of items at the front end of the array and return the length of the array.

4. array Functions

Sort can sort arrays, and reverse will flip the order of array items.

Similar to most sorting functions, sort can accept a comparison function to achieve custom sorting of Arrays:

Concat (): concatenate a new array based on the original array:

var colors = ["red","green" ];console.log( colors.concat(["blue","yellow"]) );

Slice (): Get a part of the array as the new array:

var arr = [1, 2, 3, 4, 5];console.log( arr.slice(2, 4));

Splice array: insert, delete, or replace items in the array:

(1) Delete

 var colors = ['r', 'g', 'b']; var removed = colors.splice(0, 2); console.log(removed);

(2) Add

var colors = ['r', 'g', 'b'];var removed = colors.splice(1, 0, "added");console.log(colors);

(3) Replacement

var colors = ['r', 'g', 'b'];var removed = colors.splice(1,1 , "redd","blue");console.log(removed);

8. Date type

The valueOf method of Date type does not return a string at all, but returns the millisecond representation of the Date. Therefore, you can directly use the comparison operator to directly compare the date value:

var date1 = new Date(2007, 1, 1);var date2 = new Date(2007, 1, 2);console.log( date1 < date2 );

Date component method. For more information, see the documentation. Important:

GetTime (): returns the number of milliseconds of the date, consistent with valueOf.

SetTime (): set the date

GetFullYear (): gets the four-digit year.

GetMonth (): Get month

GetDate (): returns the number of days in the month.

......

9. RegExp type

ECMAScript supports regular expressions through the RegExp type.

Varpattern =/pattern/flags

There are three types of flags:

G: indicates the global match mode. The mode is applied to the entire string, instead of stopping when the first match is found.

I: case-insensitive matching

M: multi-line mode. When the end of a line of text is reached, the next line of text will be searched.

Another way to create a regular expression is through the RegExp object:

Var pattern = newRegExp ("[bc] at", "I ");

The two parameters passed to RegExp are strings, and the literal amount of the regular expression cannot be directly transferred to RegExp. Because the pattern parameter of the RegExp constructor is a string, double escape is required for characters in some cases. All metacharacters must be double escaped.

RegExp instances all have the following attributes:

(1)GlobalIndicates whether the g flag is enabled

(2)IgnorecaseIndicates whether the I flag is enabled.

(3)LastIndexIndicates the character position of the next match, starting from 0.

(4)MultilineWhether the m flag is enabled

(5)SourceString representation of a regular expression, which is returned literally.

var pattern1 = /\[bc\]at/i;var pattern2 = newRegExp("\\[bc\\]at", "i");console.log(pattern1.global);console.log(pattern1.ignoreCase);console.log(pattern1.multiline);console.log(pattern1.lastIndex);console.log(pattern1.source);console.log(pattern2.source);

RegExp objects have two common instance methods: exec () and test ();

Exec is designed for capture groups. exec receives a string parameter and returns an array containing matching items:

Test () receives a string parameter. If the parameter matches the regular expression, true is returned. Otherwise, false is returned.

Features not supported by ECMAScript Regular Expressions:

(1) match the \ A and \ Z anchor starting and ending strings

(2) lookbehind

(3) Parallel set and intersection class

(4) atomic groups

(5) Unicode support (except for a single character)

(6) named capture group

(7), s, and x matching Modes

(8) condition matching

(9), regular expression comment

10. Function Type

Each Function is an instance of a Function and has the same attributes and methods as other reference types. Because the function is an object, the function name is actually a pointer to the function object.

Because the function name is only a pointer to a function, the function name is no different from other variables that contain the Object Pointer. A function can have multiple names:

function sum(a, b){         returna + b;} var antSum = sum;console.log( antSum(1, 2) );sum = null;console.log( antSum(1, 2) );

Think of the function name as a pointer, which explains why ECMAScript does not have the concept of function overloading.

When the parser loads data, it does not treat the function declaration and function expression equally: the parser will first read the function declaration and make it available before executing any code. For function expressions, the parser will be interpreted and executed only when it is executed to its code line. The following method may cause errors during the execution period:

console.log( sum(1, 2) );var sum = function(a, b){         returna + b;}

Because the function name in ECMAScript is a variable, the function can also be used as a value. That is to say, a function can be passed to another function just like a parameter, and a function can be returned as the result of another function. In this sense, the function is a first-class citizen in ECMAScript.

You can return a function from a function. For example, you can create a function for comparing property names (for sorting ):

function createCompare( prop ){   return function( obj1, obj2 ){       var v1 = obj1[ prop ];       var v2 = obj2[ prop ];       if( v1 < v2 ){           return -1;       }else if( v1 > v2 ){           return 1;       }else{           return 0;       }     }; }   

Note that if return v1-v2 is used here, it is incorrect, because for strings, The result returned by string Subtraction is NaN.

The function has two special attributes: this and arguments. Here, arguments is a class array object, which contains all the parameters of the input function:

functiontest(){         console.log( arguments );         console.log(arguments.length );}test(1,2, 3, 4, 5);

Although the main function of arguments is to save function parameters, this object also has a property named callee, which is a pointer pointing to having this arguments pair

Function:

function factor( num ){   if( num <= 1 ){       return 1;    }   return num * arguments.callee( num - 1 );}

Using arguments. callee ensures that recursion (decoupling) can be completed correctly regardless of the name used by the function ).

Another special object inside the function is this,This is the scope of the function during execution.(When a function is called in the global scope of the current webpage, this object references window)

Function Attributes and Methods: The ECMAScript function is an object, so the function also has attributes and Methods. Each function contains two attributes: length and prototype, length indicates the number of name parameters to be received by the function:

function sum(a, b){     return a + b;}console.log(sum.length);

Prototype is the most important attribute of ECMAScript (see chapter 6)

Each function contains two inherited methods: apply and call. The purpose of these two methods is to call a function in a specific scope, which is actually equal to setting the value of this object in the function body:

Function sum (a, B) {return a + B;} function callSum (a, B) {// The function is called globally, therefore, this = window return sum. apply (this, arguments);} function callSum2 (a, B) {return sum. apply (this, [a, B]);} console. log (callSum (1, 2); console. log (callSum2 (2, 3 ));

The call method and apply method have the same effect. The difference between them is that the method of receiving parameters is different:

function callSum(a, b){         return sum.call(this, a, b);}console.log(callSum(1, 3));

In fact, passing parameters is not really useful for call and apply. What they are really powerful is that they can expand the scope on which the function depends. :

var color = "red";var o = {color : "blue"};function sayColor(){   console.log(this + " this.color: " + this.color);}sayColor();sayColor.call(this);sayColor.call( o );

The biggest benefit of using call and apply to expand the scope is that the object does not need to have any coupling relationship with the method.

11. Basic packaging type

To facilitate the operation of basic type values, ECMAScript also provides three special reference types: Boolean, Number, and String.

The difference between the reference type and the basic packaging type is the lifetime of the object. Instances of the reference type created using the New operator are stored in the memory until the execution flow leaves the current scope, the automatically created automatically wrapped object only exists in the execution instant of a line of code and is immediately destroyed. This means that attributes and methods cannot be added for basic type values:

vars = "some test";s.color= "red";console.log(s.color );//undefined

It is not recommended to explicitly create objects of the basic packaging type.

ToFixed, toExponential, and toPrecision are two methods for formatting numeric values.

When the typeof operator is used to test the value of the basic type, "number" is always returned. When the Number object is tested, the object is returned. the Number object is an instance of the Number type, while the basic type is not.

String type:

Each instance of the String type contains a length attribute, indicating the number of characters contained in the String (Multi-byte characters are still counted as one character ):

Var s = "some test good"; console. log (s. length );

CharAtAndCharCodeAtUsed to access specific characters in a string. CharAt returns a single character at a given position, while charCodeAt returns the character encoding at the specified position:

vars = "hello";console.log(s.charAt(2));//lconsole.log(s.charCodeAt(2));//108

ConcatConcatenates one or more strings to return the new string.

Slice, substr, substring: Create a New String Based on the substring (they do not modify the value of the original string, but only return a basic string value ):

String. slice (start, end );

String. substring (start, end );

String. substr (start, len );

IndexOfReturns the position of the substring. If not found, returns-1 (Backward Search)

LastIndexOfReturns the position of the last occurrence of the substring (Forward search)

You can find all the positions of all substrings in the string Through cyclic search:

String Matching: match and search

Easy to mix: test () and exec () are regular expression methods, RegExp. test (str), RegExp.exe c (str );

Match and search are string operations, str. match (RegExp), str. search (RegExp)

ReplaceThe first parameter can be a RegExp regular expression or string. If it is a string, it will only Replace the first substring. If you want to replace all strings, you can provide a regular expression, and specify the global flag ). the second parameter inserts the value obtained by the regular expression operation into the result string:

var text = "cat, bat, sat, fat",result = text.replace(/(.at)/g, "word($1)");console.log( result );

The second parameter of replace can also be a function: if there is only one matching item, three parameters will be input to this function: the start position of the pattern match, and the original string:

function htmlEscape( str ){   return str.replace(/[<>"&]/g, function( match, pos, orig){       switch( match ){           case "<":                return "<";                break;           case ">":                return ">";                break;           case "&":                return "&";                break;           case "\"":                return """;                break;       }   });}

SplitUsed for mode separation:

var colorStr = "red, blue, green,red";console.log( colorStr.split(","));console.log( colorStr.split(",",2) );

FromCharCodeReceives one or more character encodings and converts them into a string:

var str = String.fromCharCode( 104, 101,108, 108, 111 );console.log( str );

12,Built-in object

Global Object: attributes and methods of a Global object that do not belong to any other objects. In fact, there are no Global variables or Global functions. All the attributes and functions defined in the Global scope are the attributes of the Global object.

URL encoding method:

The encodeURI and encodeURIComponent () Methods of the Global object can encode the URI.

EncodeURI is mainly used to encode the entire URI, while encodeURIComponent is mainly used to encode a certain segment of URI. The main difference is that encodeURI does not encode special characters belonging to the URI, such as colon:, forward slash/, question mark? And well #; while encodeURIComponent will encode any non-standard characters it finds:

var uri = "http://www.prox.com/illvalue#start";//http://www.prox.com/ill%20value#startconsole.log( encodeURI(uri) );//http%3A%2F%2Fwww.prox.com%2Fill%20value%23startconsole.log( encodeURIComponent(uri) );

The two methods corresponding to encodeURI and encodeURIComponent are decodeURI and decodeURIComponent, which correspond One to One. decodeURI can only decode the characters encoded using encodeURI. Similarly, decodeURIComponent can only decode characters encoded using encodeURIComponent.

Eval:

You can define a function in eval. This function can be called externally.

Eval ("functionsayHi () {console. log ('Hi ');}");

SayHi ();

Window object: Although ECMAScript does not point out how to directly access the Global object, the Web browser implements this Global variable as part of the Window object. Therefore, all variables and functions declared in the global scope are the properties of the window object.

var color = "red";function sayColor( ){   console.log(window.color);}window.sayColor();

Math object:

Attributes of the Math object include:

Math. E

Math. LN10

Math. LN2

Math. LOG2E

Math. LOG10E

Math. PI

Math. SQRT1_2

Math. SQRT2

Math object method:

(1) min and max methods are used to determine the maximum and minimum values of a group of values.

(2) Rounding Method: Math. ceil (), Math. floor (), Math. round

(3) random () method. Return a random number between 0 and 1, excluding 0 and 1. Apply the formula:

Val = Math. floor (Math. random () * Total number of possible values + the first possible value) You can select a value in a range.

functionselectFrom(low, high){     var nums = high – low + 1;     return Math.floor( nums * Math.random() + low );}console.log(selectFrom(2,10));

(4) abs (num), exp (num), log (num), pow (num, power)

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.