Reference types of JavaScript advanced programming (top)

Source: Internet
Author: User

A reference type is a more complex type. In object-oriented programming, reference types are often used, which can be said to be the core of programming languages. There are several reference types built into JS, which are described below in one by one.

Built-in reference types

Object type

1, declaration method: Use the new operator directly (const data = new Object ()) and use the object literal (const data = {}) two ways. With object literals, you can write properties and methods within curly braces, or you can write nothing. It is important to note that although nothing is written, the object is not an empty object, it contains some default properties and methods.

2, Access value: You can use the object name directly point property name Access value (const DATA = {name:123}; Console.log (Data.name)), can also object name block number, write property name in square brackets access value (const Data = {name:123}; Console.log (data["name"]). A variable can be written in square brackets when accessed using square brackets.

Array type

The array of JS is somewhat different from other programming language arrays, its value can be any type, string, numeric, object can be, and its length is dynamic, will be adjusted dynamically as the merit increases. There are two different ways of declaring an array (the array contains up to 4,294,967,295 values), the first using the constructor (const A = new Array ()), and the second using the literal (const A = []). Use the constructor to create an array, you can pass the parameter, or do not pass the parameter, the array will be a zero-length array, the argument, the total support of the two methods, for example:

1 //How constructors are created2Let B = () ={3Const A =NewArray ();//To create an array of length zero without a pass parameter4 5 Console.log (a)6           }7 8b = () = ={9Const A =NewArray (3);//Create an array of length 3Ten  OneConsole.log (a[2]);//because there is no value, it is undefined A           } -  -b = () = ={ theConst A =NewArray ("Blue", "green", "red");//creates a length of 3 and contains 3 worth of arrays -  -Console.log (a[2]);//The value is red because it has a value -}
Constructor Declaration Array

Example of how to create a literal:

1  //How to create a literal2b = () = ={3Let A = ["3", "5", "6"];//Create an array4 5A = [1, 2,];//create two worth of arrays, ie create three worth of arrays6 7A = [,,,,,,];//since there is no specific value written, the values inside the array are undefined8 9A.length = 3;//Modifying the length changes the array, so you can remove the value by modifying the length. Ten  OneA[7] = 5//adds a value to the array. The length becomes 8, and the part between the intervals is replaced by undefined.  A  -Console.log (a[1]);//accessing the 2nd value in the array -}
How to create a literal

Array detection

The JS array provides two ways to detect arrays, the first of which is to use the instanceof operator to determine if a variable is an instance of an array. However, there is a problem with this detection method, that is, when using multiple frames, another framework has its own encapsulated array constructor, this time there is a problem, you can not determine whether the variable is a native array. The second new Api,array.isarray () method uses ES5. ES5 proposed this method in order to solve the problem of the first method. Cases:

 1  const A = () =>{ 2  const B = [3,2,4,1];  3  //  The instanceof operator detects  4  const C = b instanc EOF  Array; //  returns True  5  6  //< /span>array.isarray  7  8  const D = array.isarray (b); //  returns True  9 } 
View Code

Conversion method

The array is converted in several ways: ToString (), tolocalstring (), ValueOf (), join (). ToString () changes the array to a comma-delimited string, and the background invokes each value's own ToString () method when it is converted. The result of the TOLOCALSTIRNG () conversion and the result of ToString () are generally the same, and also a comma-delimited string, but the difference is that, when converted, the background call is every worthwhile tolocalstring () method. ValueOf () returns an array. Join () receives a parameter that specifies what character the array is, as a connector, to concatenate the array into a string. If the parameter is not passed or undefined, the values are concatenated by default with commas. Cases:

1Const AH = () ={2Const B = [3,2,4,1];3 4Const C = {5ToString: () =>{return"Y"},6toLocaleString: () =>{return"Y" }7               },8D = {9ToString: () =>{return"X"},TentoLocaleString: () =>{return"X"} One               }, Af =[c,d]; -  -B.tostring ()//"3,2,4,1" the  -B.tolocalestring ()//"3,2,4,1" -  -B.valueof ()//3,2,4,1 +  -B.join ("-")//"3-2-4-1" +               //the value is "y,x" because the background calls each worthy ToString method. AF.tostring ()//"Y,x" at  -F.tolocalestring ()//"Y,x" -}
View Code

Stack method (pop and push)

The stack is a last-in-first-out data structure, and pop and push implement this feature. Cases:

1 // Stack Method 2             Const Strack = () ={3let                     a = [+]; 4 5                     // LIFO, adding elements at the end of the array, and returning new lengths 6 7                     // First Out, delete an element at the end of the array and return the item that was deleted 8             }
View Code

Queue method (Shift)

The queue is a first-in-a-kind data structure, in JS, through the push and shift simulation queue, through unshift and pop implementation of the reverse queue. See below for specific examples:

1 //Queue Method2 3Const Queque = () ={4Let A = [3,4];5 6                 //forward Queue7A.push (5);//add an element to the tail of an array8A.shift ();//deletes an element at the head of the array and returns the deleted item9 Ten                 //Reverse Queue OneA.unshift (3)//adds an element to the head of the array and returns the new length AA.pop ()//deletes an element from the tail and returns the item that was deleted -}
View Code

Sorting methods (reverse and sort)

1 //Sorting Methods2Const SORT = () ={3Let A = [4,3,5];4 5                  //reverse and sort are replaced by a new array of ordered rows .6A.reverse ()//Flip Array Order7 8A.sort ()//The value of each item is converted to a string for comparison, so the sorting result is not satisfactory, usually by passing in the callback function to implement the sort. 9 TenA.sort ((Val1,val2) =>val1>val2);//3,4,5 One}
View Code

Operating methods (concat, slice, and splice)

1  //Operation Method2Const DOS = () ={3Let B = [3,5,3];4                 //The incoming array value, the connection generates a new array and returns5Let d = B.concat ()//a copy of the original array is returned because no arguments are passed6D = B.concat ("5", ["9", "10"])//return value [3,5,3,5,9,10]7                 //starts the intercept at the specified position of the array, returning the new array generated after the intercept. Two parameters start and end,8                 //only start will be intercepted until the end. Parameter supports negative values. If the argument is negative, the array length is added9                 //parameter values to determine the locationTenB.slice (1)//[5,3] OneB.slice (ON)//[5] AB.slice (-1)//[3] -B.slice ( -3,-1)//[3,5] -B.slice ( -1,-2)//the starting position is greater than the end position, returning an empty array the                 //The Delete, insert, and replace operations are determined based on the parameters they pass in. The first parameter is the start position -                 //The second parameter is to delete a few. The third parameter is the new value to insert -                 //Splice will change the original array -B.splice (0,1)//delete operation returned [3] +B.splice (0,0,4)//insert operation [4,3,5,3] -B.splice (0,1,4)//Replace operation [4,5,3] +                A}
View Code

Location methods (IndexOf and LastIndexOf)

 1  const POSITION = () =>{ 2  const POS = [4,3,2];  3  //  check Find if the element exists within the array, there is a return element position, there is no return-1. Find rules, compare by = = =.  4  pos.indexof (3) //  returns 1  5  6  //  7  pos.lastindexof (3) // 
    
      returns 1 
     8 } 
View Code

Iterative methods

1 //Iterative Methods2Const Fors = () ={3Const D = [3,4,5,6];4                 //The judgment result is true to return true. The parameter is a callback function, the callback function has three arguments, and 1 is the current item. 2 index. 3 Array Objects5D.every (e=>e>5);6                 //The judgment result has a true and returns true. Use the same way as every7D.some (e=>e>5)8                 //returns a value that meets the criteria and generates a new array9D.filter (e=>e>5)Ten                 //returns the value after the operation and generates a new array OneD.map (e=>e-1) A                 //simply perform iterative operations -D.foreach (e=>Console.log (e)) -}
View Code Merge Method
1 Const c = () ={2                 const F = [3,4,5,6]; 3                 // accumulate (subtract, multiply, divide) operations on an array and return its results. The callback function has two arguments, the first is the result of the previous element, and the second is the current item 4                 f.reduce ((sum,val) =>sum + val); 5                 // same as reduce, but loops from the end to the beginning 6                 F.reduceright ((sum,val) =>sum + val); 7             }
View Code

Reference types of JavaScript advanced programming (top)

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.