JavaScript reference types

Source: Internet
Author: User
Tags numeric value

Creation of the object:
1.new constructor var person = new Object (); Person.name = "Qi";
2. Object literal (preferred) var person={name: "Qi", age:22}///can also "name": "Qi" Here the name will be automatically converted to a string
or Var person={}; Equivalent to construction

. representations and [] representations
Person.name person["name"] unless you have to use variable access, you typically use. To access the property

Array type
The Ecmascrip array differs from other languages in that it can dynamically change the length, and each array element can hold different data types.
Creation of arrays:
var arr = new Array ();
var arr = new Array (20);
var arr = new Array (' Red ', ' green ', ' blue ');
You can also omit the new
var arr = Array (' Red ', ' green ', ' blue ');
When a parameter passes in a value, an array of the specified number of items is constructed
When a non-numeric value is passed in, an array containing only the values is created

Array literal method, which does not call the constructor (preferably a plural number)
var colors = ["Red", "green", "blue"];
var names = [];
Using an index to access an array
Attention:
1. The length of the array is changeable, allowing the array length to be increased when the value is assigned
COLORS[3] = "Brown"; Added item Fourth
2. The length of the array is not read-only, you can set the length of the array by setting it (remove or add)
colors.length=2; The colors[2] = undefined
or colors.length = 4; All the extra items are undefined.
or colors[colors.length] = "block"; Add a new item at the end

Array.isarray (value)//detection is not an array
Conversion method:
All objects will have tolocalestring (), toString (), and valueof () methods.
The exact conversion is as follows (generated with, split string)
Alert (colors.tostring ()); Red,green,blue, the ToString method of each item is called
Alert (colors.valueof ());//red,green,blue itself returns an array
alert (colors);//red,green,blue

Colors.tolocalestring (); The toLocaleString () method of each item is called.

1 varPerson1 = {2toLocaleString:function(){3         return"Zhd"4     }5Tostring:function(){6         return"Qi";7     }8 }9 varPerson2 = {TentoLocaleString:function(){ One         return"ZHD2" A     } -Tostring:function(){ -         return"Qi2"; the     } - } - varPeople =[Person1,person2]; -Alert (people.tostring ());//Qi,qi2 +Alert (people.tolocalestring ());//ZHD,ZHD2

The join () method, which is used by default, is separated by a join that specifies a delimiter that separates the
Alert (Colors.join ("| |)"); red| | green| | Blue

Using arrays to mimic the stack's characteristics
Stack: Linear data structure, only at the top of the stack to carry out the stack operation, advanced
var colors = new Array ();
Colors.push ("Red", "green"); The introduction of two

var items = Colors.pop (); Take the top element of the stack. And then out of the stack, for traditional languages,
After the data is out of the stack, the length minus 1,javascript will automatically reduce the length
, in the same vein, the stack is
Queue: 1. Insert push element at tail, remove shift element at top, same as stack section
2. Use Unshift (remove at the end) and pop (insert element at the top) combination,
The queue can be processed in turn
Array sorting:
The default array ordering is prone to confusion when sorting strings. For example: in ascending order,
It will rank "10" in front of "5" because 1 < 5, so it is necessary to specify a collation
Cases:

1 vararr = [0,3,5,10,9];2Alert (Arr.sort ());//the output 0,10,3,5,9 of the disorder3 functionCompare (value1,value2) {4     if(Value1 >value2) {5       return-1;6}Else if(Value1 <value2) {7       return1;8}Else{9       return0;Ten     } One } AAlert (Arr.sort (compare));//correct sort: 0,3,5,9,10

In the Chrome V8 engine, the sort underlying implementation has a parameter that specifies the callback function that needs to be called.
The rules can be specified in the function, and V8 gives two kinds of underlying sort insertionsort and QuickSort
Source Address: https://github.com/v8/v8/blob/master/src/js/array.js#L726
Different JS engines, the exact sort algorithm will not be the same

The inverse function of the array reverse ();

"Stitching" of arrays: concat
In using the Concat method, it copies the original array and stitches the parameters in the concat into the array
The back. If the argument is an array, then each item of the parameter array is "spliced" on the arrays, if the parameter
is not an array, it is simply added to the end of the array
Note: The original array is not changed, and the concatenation is just a new copy of the array
var colors = ["Red", "green", "blue"];
var colors2 = Colors.concat ("Yellow", ["Black", "Brown"]);

alert (colors); Red,green,blue
alert (colors2);//red,green,blue,yellow,brown

Interception of arrays: 1.slice (Start,end) The method can intercept a part of a new array on an existing base array.
Slice when there is only one parameter: intercepts all items from the current position to the end of the array
Two parameters, intercept from the first parameter position,
All items to the second parameter position (items that do not include the end position)
Arguments can be negative, or negative, basically equals the position represented by the forward number argument from the end of the array
Both: If the array has 5 items, slice ( -2,-1) is the same as slice (3,4).

Use of 2.splice methods: Delete Insert Substitution
Splice (Start, DeleteCount, [item1[, item2[, ... [, Itemn]]])
Delete: When there are only the first two parameters, the array begins with the start subscript, deleting deletecount elements
When the parameter has only the start parameter, it deletes the element from the start subscript to the last
Insert: When DeleteCount is 0, a new item element is inserted at the start position of the array.
Replace: When DeleteCount is 0, the start position of the array is started, and the DeleteCount element is deleted.
Inserts a new item element from the start position.

When the parameter is negative, the parameter specifies the position from the end of the array element (-1 refers to the penultimate element in the array, and 2 refers to the second-to-last element in the array). )

Splice (0,2); The original array deletes the first two items of the array, returning the first two items
Splice (2,0, "red")//The original array adds a new item to the second position red, returns 0, no delete will return an empty array
Splice (2,1, "red")//The original array replaces the 1 items following item 2nd with red, returning an array of the replaced data

The original array of splice operations, splice the original array will change the length of the original array and the data changes, the corresponding
The splice method returns an array of the data that is being manipulated.

Location Methods IndexOf () and LastIndexOf ()
Two parameters: The index position of the search term and the start of the lookup (optional)
Returns the index position of the search item (no search to return-1)
Iterative methods: 5, each iteration method has passed a method (a set of rules), so that each item in the array is executed side, return
Returns the logical value of the array after each execution method;
Temporarily omit the original book 98 pages
Reduction method: Reduce the scope omit the original book 98 pages

Date Type: var now = new Date (); If you have arguments, you want to create an object from a parameter, the parameter accepts only the millisecond value
Date.parse () converts a date string to milliseconds, which can be omitted without writing, system default call
DATE.UTC (); Converts a date string to milliseconds, as an example:
GMT January 1, 2000 3:0 0 seconds 0 milliseconds (month and year must provide parameters, others default is 0, starting from 0)
var d = new Date (DATA.UTC (2000,0,3,0));

Constructors can also write if the first argument to the constructor is a numeric value
var d = new Date (2000,0,3,0);

Date.now (); Returns the number of milliseconds for the date and time that this method was called
var start = Date.now ();
DoSomething ();
var stop = date.new ();
return stop-start;

In browsers that do not support the Date.new method, you can use "+" to convert to a string and achieve the same effect
var start = +date.now ();
DoSomething ();
var stop = +date.new ();
return stop-start;

The date can be compared directly to the size, and the number of milliseconds is compared by default
Several getter/setter of the date (can get/set milliseconds, year, month, day ...) original book 102 pages

Regular Expressions: Original book 103 pages

function functions: They are actually objects, each function is an instance of a function, each of which is actually a pointer to a function object
function sum (num1,num2) {return num1+num2;};
And
var sum = function (num1,num2) {return num1+num2;};
Equivalent, use sum directly when calling

Because the function name is a pointer to a function object, a function may have a number of functional names
var autosum = sum; Without () refers to the function pointer and not to the function object
Alert (AutoSum (10,10)); 20, even if sum = Null,autosum works equally

No reload!!! Because there is no specific method signature, in fact, the function that is declared the second time is considered the first function
Declaration of reference
function declaration and Function expression: function declaration that functions sum () {} is pre-loaded into the execution environment
The var sum = function () {} is not loaded in advance and should be used after the expression when using sum, otherwise
Unexpecter identifier (unexpected identifier) error occurred

Pass as value: The function name can also be passed as a value because it is itself a variable.
That is, you can pass a function as a parameter, or you can pass the return result of a function as a parameter.

1 function callsomefunction (somefunction,someargument) {2     return SomeFunction (someargument); // the incoming function can be executed inside the function body. 3 }// to access a pointer to a function without executing a function, you must remove the function's "()"

You can also write a function in another function example

functioncreatecomparisonfunction (PropertyName) {return function(object1,object2) {varValue1 =Object1[propertyname]; varValue1 =Object2[propertyname]; if(Value1 <value2) {            return-1; }Else if(Value1 >value2) {            return1; }Else{            return0; }    }; //do not forget this semicolon as a return statement to see}vardata = [{"Name": "Zhd"},{"name": "Qi"}];d Ata.sort (createcomparisonfunction ("Name") ; alert (data[)0]. Name);//Zhd

Function Internal properties: two special objects This,arguments
Arguments contains parameters for all incoming functions, and there is a callee property, which is a pointer to the owning
The function of this arguments. Objective: The decoupling and relation between function and code can be realized.
Factorial example parsing:

functionfactorial (num) {if(Num < 1){        returnnum; }Else{        //return num * factorial (NUM-1)//First notation        returnnum * Arguments.callee (NUM-1)//The second type of notation    }}//NotevarTruefactorial = factorial;//truefactorial and factorial point to the same function objectfactorial =function{    return0;//The function that factorial points to is changed, so in the factorial original factorial function, if you use the                //The first one, then it will not return the correct result when calling Truefactorial                //because the changed factorial is called when the function body factorial recursion is evaluated and the result is returned 0}alert (truefactorial (5));//returns 120 the first form of a notation returns 0

This: Refers to the function that is used to execute an Environment object who refers to, and to whom, if no object references the function (
In the global environment) then it will point to the Window object

Caller: Retains a reference to the function that called the current function, cannot assign a value to the property, or null if it is a global environment

1 function outer () {2    inner (); 3 }4funcion inner () {5    alert (inner.caller); 6     // decoupling 7 }8// Returns the source of the outer because Inner.caller points to the outer function

Properties and methods of the function: Remember::: The function is an Object!!!
Each function contains two attributes length (the number of arguments to the function) and prototype (sixth chapter)
Contains two non-inherited methods apply () and call () are used to invoke a function in a particular scope, which is actually equal to
Set the value of the function body this

Apply () Takes two parameters, the first of which runs the scope of the function,
Another parameter is an array of arguments (which can be an instance of an array, or a arguments object)

1 functionsum (num1,num2) {2     returnnum1+num2;3 }4 functionCallSum1 (num1,num2) {5     returnSum.apply ( This, arguments);//this refers to the CALLSUM1, which points to the outermost function6 }7 functioncallSum2 (num1,num2) {8     returnSum.apply ( This, [num1,num2]); 9 }TenAlert (CALLSUM1 (10,10));// - OneAlert (callSum2 (10,10));// 

About this point of http://www.cnblogs.com/pssp/p/5216085.html
Call () is the same as apply, except that the second parameter is listed once

1 functio callSum3 (num1,num2) {2return sum.call (this, num1,num2); 3 }   



!!! The most powerful place to apply and call is to expand the scope of the function to survive!!!

1Window.color = "Red";2 varo = {color: ' Blue '};3 functionSaycolor () {4Alert This. color);5 }6Saycolor.call ( This);//Red This refers to window execution in the global environment7Saycolor.call (window);//Red similarly8Saycolor.call (o);//Blue The This object in the function body points to O, enabling the decoupling of the function object from the O object and9 Ten //var o = { One //color: ' Blue '; A //function Saycolor () { - //alert (this.color); - //     } the // } - //o.saycolor = Saycolor; - //O.saycolor (); -  + //or: - varo = { +Color: ' Blue ', ASaycolor:function (){ atAlert This. color); -     } -  } -O.saycolor ();


Bind (); Binds the function itself to the parameter being passed in
var objectsaycolor = Saycolor.bind (o); At this point the function body this points to the parameter O
Objectsaycolor (); Blue will return even if it is running in the global environment.

Each function inherits the ToString (), tolocalestring (), and ValueOf returns the function code

  

JavaScript reference types

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.