Array of reference types the most complete explanation

Source: Internet
Author: User

Array type

Summarize the array type today. The array in JS is a very powerful feature. Has a lot of flexibility, there are two aspects of the characteristics

1, each item of the array can hold any data type, 2, the size of the array can be dynamically adjusted; see the following example:

           varOne=NewArray ();//Empty Array           vartwo=NewArray (5)//array with length 5           varThree=NewArray ("Double", 3)//An array that contains double and 3           varFour=[]//use [] to denote           varfive=[1,2,3,4] Console.log (five[0])//1 Index of array starting from 0, length-1Console.log (Five.length)//4 array size length is 4five.length=10Console.log (five[4])//indexes from 4 to 9 are undefined
Detection type

As discussed earlier, for reference types, you can use instanceof to detect that an object is not an array, which is only appropriate for a single global environment. For a few global environments, you can use the ES5 new Array.isarray () method

          var one=[]          ifinstanceof  Array) {                  Console.log ("true")          }           if (Array.isarray (one)) {                  Console.log ("true")    IE9 support          }
Conversion method

All we know is that all objects have the ToString (), tolocalestring (), and valueOf () methods

For arrays: ValueOf () returns the array itself; ToString () returns a comma-delimited string of each string in the array that is worth concatenation (each item of the array calls the ToString () method)

          varOne=[1, "2", "great"]; varTwo=one.tostring ();//array Each item calls the ToString () method, which consists of a string          varThree=one.valueof ();//returns the array itself          varFour=one.tolocalestring ()//each item of the array calls the toLocaleString () method, which makes up the stringConsole.log (typeofboth)//stringConsole.log (typeofTwo[0])//stringConsole.log (Array.isarray (three))//trueConsole.log (typeofFour//stringConsole.log (typeofFour[0])//string          varfirst=[1,2,3,4] Console.log (First.join ("||"))//the Join () method is primarily a connection, with the default or comma

Add a little bit about the difference between ToString () and tolocalestring (), mainly on dates and numbers

1, the difference in date, the locale represents the concept of internationalization and localization.varDate=NewDate (); Console.log (Date.tostring ())//Default Date Mon Jan 2018 16:01:34 gmt+0800 (China Standard Time)Console.log (date.tolocalestring ())//Localization Date 2018/1/29 pm 4:01:342, the difference between the number over 3 digitsvarnum1=100; varnum2=1000000; Console.log (Num1.tostring ())// -Console.log (num1.tolocalestring ())// -Console.log (num2.tostring ())//1000000Console.log (num2.tolocalestring ())//1,000,000 every 3 0 will have commas
Methods for manipulating arrays

Stack Method (LIFO): Push (), push-in and pop (), pop-up two

         var one=[1,2]         one.push (3,4)       // Add 3,4 console.log at the end         (one)    // 1,2,3,4            var two=one.pop ()   // Delete and return the end number         Console.log (one)    //  the         Console.log (both)    //4

Queue Method (Advanced post-Exit): Shift (), remove and Unshift (), add two

         var one=[1,2]         one.unshift (3,4)    // Add 3,4 Console.log at the beginning         (one)    // 3,4,1,2            var two=one.shift ()   // Delete and return first number         Console.log (one)    // 2,3,4         Console.log (both)    //3

Reorder Methods : Reverse () and sort () methods, their return values are sorted array

        //reverse () method        varone=[1,2,3,4] Console.log (One.reverse ())//4,3,2,1 Flipping the order of array items                //sort () method        vartwo=[0,5,10,15] Console.log (Two.sort ())//The 0,10,15,5 sort method is sorted by default in ascending order, which first calls the ToString () method of each item and sorts it according to the rules of string                //sort accepts comparison functions
//Common comparison varthree=[0,5,10,15] varThrees=three.sort (RANK1)//Call comparison function functionRank1 (num1,num2) {if(num1<num2) { return-1 } if(num1>num2) { return1 } Else{ return0 } } functionRANK2 (num1,num2) {//or so returnNum1-num2//num1-num2 is ascending; Num2-num1 is descending} console.log (Threes)//0,5,10,15 //Comparison of Objects varobjectlist=[] functionPerson (name,age) { This. name=name; This. age=Age ; } Objectlist.push (NewPerson ("Double", 5)) Objectlist.push (NewPerson ("single", 15)) Objectlist.push (NewPerson ("another", 10)) Objectlist.sort (functionRank (A, b) {//sort the comparison function returna.age-B.age}) for(vari=0;i<objectlist.length;i++) {//walk through it againConsole.log ("name" +objectlist[i].name+ "age" +objectlist[i].age)}

Concat () Method: Creates a new array based on all the items in the current array ( creates a copy of the current array, adds the accepted parameters to the end of the array ), and has no effect on the original array .

Slice () method: creates a new array based on one or more items in the current array , with more rules and no effect on the original array .

These two methods are noteworthy and have no effect on the original array, while other methods are based on the operation of the original array

       varone=[1,2,3]       varTwo=one.concat (4,5,[6,7])
Console.log (one)//[1,2,3] created a replica console.log (one)//[1,2,3,4,5,6,7]varone=[1,2,3,4,5] Console.log (One.slice ())//intercept the entire arrayConsole.log (One.slice (3))//4,5 Index 3 start to endConsole.log (One.slice (0,3))//no index 3 includedConsole.log (One.slice (1,-1))//negative, 1 is the penultimate, 2 is the secondConsole.log (One.slice ( -4,-1))//plus length, 2,3,4.

The universal Dafa for modifying array items: Splice () method

Delete: Specify 2 parameters, the first position to delete, and the number of items deleted

Insert: Specify 3 parameters, starting position, 0 (number of items to delete), item to insert

Replace: Specify 3 parameters, starting position, item to delete, any number of items to insert

       var one=["A", "B", "C", "D"]       one.splice (3,1)           //D       Console.log (one)          //a,b,c       one.splice (2,0, "E", "F")       Console.log (one)          //  a,b,e,f,c    Add is in front of add       one.splice (2,1, "G", "H")       Console.log (one          ) // A,b,g,h,f,c

Location method

The IndexOf () and LastIndexOf () methods, the subparagraphs (optional) to find represents the index at which to find the starting point; IndexOf to look backwards from the beginning of the array, LastIndexOf from the front of the array

Returns the position of the item in the array and returns 1 if it is not found, using the congruent operator

      var one=[1,2,3,2,4]      console.log (One.indexof (1))     //0 Returns the index value of the item to find      Console.log (One.indexof ("1"))   // 1 because the comparison uses the congruent operator, you cannot find the direct return-1      Console.log (One.indexof (4,2))   //5 from index to 2 find      //3
Iterative methods

The 5 iterative methods specified by ES5 accept two parameters: the function that runs on each item and (optionally) the scope object that runs the function-affects the This value

The function accepts three parameters: each element in the item array, the index of each element in the index array, the array itself, the item is required, and the other is optional

every and some are the logical determinant of an array, which is determined by applying the specified function, returning a Boolean value every the passed-in function returns true for each entry, which is equivalent to&&and some returns true if any of the functions passed in is true, equivalent to||
varone=[1,2,3,4,5] varEveryresult=one.every (function(Item,index,array) {returnItem>4}) Console.log (Everyresult)//Flase Not every item is greater than 4 varSomeresult=one.some (function(Item,index,array) {returnItem>4}) Console.log (Someresult)//true there are items greater than 4
filter returns an array whose elements are specified to check all elements in the array that satisfy the function condition
varone=[1,2,3,4,5,6] varFilterresult=one.filter (function(Item,index,array) {returnItem>4}) Console.log (Filterresult)//5,6 returns an array that satisfies the conditionmap Returns an array of elements that are the collection of results passed into the function
varone=[1,2,3,4] varMapresult=one.map (function(Item,index,array) {returnItem*4}) Console.log (Mapresult)//4,8,12,16 Returns an array of the result of the function
foreach is used to call each element in an array, return an element to a callback function, have no return value, and be essentially the same as using a For loop iteration groupvarone=[1,2,3,4,5,6] One.foreach (function(Item,index,array) {Console.log (item)//iteration of the 1--6     })     vartwo=[1,2,3,4]     varSum=0Two.foreach (function(item,index,array) {sum+=item//Accumulate}) Console.log (sum)//TenTwo.foreach (function(Item,index,array) {Two[index]=item+1//element Self-added}) Console.log (both)//2,3,4,5

And the method of return

Both methods of reduce () and reduceright () iterate over all the items of the algebraic group, and then build a final return value, which is traversed from the first item of the array, reduceright from the last iteration of the array;

    The basic syntax for the array.reduce (function, InitialValue)    function takes four parameters: Pre,cur,index,array    If there is an initial value, the pre is the initial value, and the pre is the first array    , Cur is the second var one=[1,2,3,4]    var sum=one.reduce (function( Pre,cur,index,array) {            return pre+cur    },0)                              console.log (sum)  //10

Pre for 0,cur 1 pre for pre and cur and 1,cur for 2 ... Go through the end

For Reduceright, there is no initial value, the pre is the last item, cur is the penultimate item, and the initial value is cur as the last.

Finally: The new method in the ES5 has a very strong function, instead of the original use for loop traversal of the various, next time with the actual project summary

Array of reference types the most complete explanation

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.