JavaScript Learning--array Types

Source: Internet
Author: User

This article is my own study summary, for beginners reference use. The great god please ignore .... Knowledge summary from JS Advanced Programming ^ _ ^

First, each entry of the array type in JS can hold any type of data. And the size of the array can be dynamically adjusted, it grows automatically as the data is added.

 * How to create an array

The first is the use of the array constructor.

var names=New  Array (); var names=array ();  // you can omit the new operator.  var names=New Array (a); var names=New Array ("Merry", "Jack", "Lily");

The second is the use of the array literal notation. Items are separated by commas.

var names=["Mary", "Rose"); var names=[];   // Empty Array var numbers=[4,5,];   // This will create an array of 2 items or 3 items, and do not do so.  var options=[,,,,];    // this creates an array that contains 4 items or 5 items. Don't do that. 

When reading or setting the value of an array, the square brackets are used and the index is provided. The different values of the index can change the structure of the array.

var numbers=[4,5,9,10,11,12];console.log (numbers[1]);  //   5numbers[6]=13;  // Add the value 13 directly to the array. At this point the length of the array is 7numbers[99]=99;   // the length of the array changes to 100. The other values are undefinedvar colors=["Red", "Green", "Orange"];colors.length=2; console.log (colors[2]);  // undefined
* Conversion Method

All objects have tolocalstring (), toString (), and ValueOf () methods.

var names=["Merry", "Lily", "Tom"//merry,lily,tom//  ["Merry", " Lily "," Tom "]console.log (names);                // ["Merry", "Lily", "Tom"]

The Tolocalstring () method often returns the same value as the first two methods, but it is not always the case. Take a look at the example below.

varperson1={tolocalestring:function () {return "Nikolaos"; }, Tostring:function () {return "Niko";}}varPerson2={tolocalestring:function () {return "Grigorios"; }, Tostring:function () {return "Greg";}}varpeople=[Person1,person2];console.log (people); //[Object,object] in ChromeConsole.log (people); /*[Object {tolocalestring=function (), Tostring=function ()}, Object {tolocalestring=function (), Tostring=function ( )}] in Firefox*/alert (people); //Nikp,gregConsole.log (People.tostring ());//Nikp,gregConsole.log (People.tolocalestring ());//Nikolaos,grigorios
* Stack method and queue method

Arrays can behave like stacks and queues, and stacks are a last-in-first-out data structure, like a dead end that allows only one person to pass through, and you can only come out when you go first. The queue is a first-in-one data structure. Listen to the name of the same as in line, who first came to the first to accept the service, the first to leave. JS specifically gives the array a few methods so that it can implement the behavior of stacks and queues.

The main method to use is push (); Pop (); Shift (); Unshift ();

The push () method is capable of receiving any number of arguments, adding them one by one to the end of the array, returning the length of the modified current array.

The Pop () method removes the last item at the end of the array and returns the item that is removed.

Shift () Moves the first item in the array, returning the item.

Unshift () adds any item at the front of the array, returning the length of the array.

varcolors=NewArray ();varCount=colors.push ("Red", "green"); Console.log (count)//2Count=colors.push ("Black"); Console.log (count)//3varitem=Colors.pop (); Console.log (item); //BlackConsole.log (colors.length)//2

Console.log (Colors.shift ()); //Red

Console.log (Colors.unshift ("Yellow", "CCCC")) //3 Yellow,ccc,green

* Reorder Method

The most straightforward approach is sort () | By default, arrays are sorted in ascending order | and reverse () | Inverse Array | method.

var number=[0,1,5,10,15];console.log (Number.reverse ())  //  [, 5, 1, 0] Console.log (Number.sort ())    // [0, 1, ten, 5]

You can see that the reverse () method reverses the array, but the sort () method does not get the effect we want. This is because the latter first invokes the ToString () method of the array and then compares the resulting string, although the value 10 is greater than 5 but goes to the front of the 5 when the string is converted. As a result, we do not generally use sort () directly for numeric arrays, but instead give sort () a sorting method.

var number=[0,1,10,5,15]; function Compare (value1,value2) {  if(value1 < value2)    return 1;}   Else if (value1>value2)     {  return -1;}     Else return 0;}}            Number.sort (Compare); Console.log (number);    // [5, 1, 0]

* Method of Operation

The Concat () method can create a new array based on all the items in the current array. Specifically, this method creates a copy and then adds the received parameter to the end of the copy, returning the new copy array.

var names=["may", "Alisa"]; var newnames=names.concat ("Jacky", ["Mark", "Mohan"]); Console.log (newnames[3]);  // Markconsole.log (newnames)   //  ["may", "Alisa", "Jacky", "Mark", "Mohan"]

The slice () method creates a new array based on one or more item (s) of the current array. When a parameter is accepted, all items from the start of the parameter's position to the end are returned. When two parameters are accepted, all items that start to end but do not include the end position are returned.

varNames=["may", "Alisa"];varNewnames=names.concat ("Jacky", ["Mark", "Mohan"])varNewnames2=newnames.slice (1);varNewnames3=newnames.slice (2,4);varNewnames4=newnames.slice ( -1,-3);varNewnames5=newnames.slice ( -2,-1); //When the parameter is negative, the length of the array is added to determine the position Console.log (newnames2)//["Alisa", "Jacky", "Mark", "Mohan"]Console.log (NEWNAMES3)//["Jacky", "Mark"]Console.log (NEWNAMES4)//[]Console.log (NEWNAMES5)//["Mark"]

The splice () method is the most powerful array method, and it has many uses. The main purpose is to insert items into the middle of the array. There are 3 ways of using it.

* Delete: You can delete any number of items, just specify 2 parameters: the location of the first item to delete and the number of items to delete. For example, splice (0,2) deletes the first two items.

* Insert: You can insert any number of items to the specified location, providing 3 parameters: Start position, 0 (number of items to delete), item to insert. For example Splice (2,0, "AAA", "BBB") insert two items starting at position 2.

* Replace: Inserts the item at the same time delete the original position of the item, equivalent to replace. You need to provide 3 parameters: The starting position, the number of items to delete, the item to insert. For example Splice (2,1, "AAA", "BBB") starting from position 2 first remove the original, and then insert the new two.

varnames=["Novia", "Alisa", "may"];varRemovednames=names.splice (0,1); Console.log (names)//["Alisa", "may"]Console.log (Removednames)//["Novia"]Removednames=names.splice (1,0, "Jacky", "Melody"); Console.log (names); //["Alisa", "Jacky", "Melody", "may"]Console.log (Removednames)// []Removednames=names.splice ("Cherry", "Tom") Console.log (names)//["Alisa", "Cherry", "Tom", "Melody", "may"]Console.log (Removednames)//["Jacky"]

* Location Method

The array instance has two positional methods IndexOf () and LastIndexOf (). Both receive two parameters: the subparagraphs (optional) to find indicates the index at which to find the starting point. The former is looking backwards from the front, and the latter is looking forward from behind.

var number=[1,2,3,4,4,5,6];console.log (Number.indexof (4))  //3 Console.log (Number.lastindexof (4))  //4console.log (Number.indexof (bis   )) // 4Console.log (Number.lastindexof (bis))   //4

* Iterative approach

Arrays have 5 iterative methods. Each method receives 2 parameters: a function to run on each item and (optionally) a scope object. Depending on the method used, the return value after the function is executed may or may not affect the return value.

*every (): Each item of an array runs the given function, and returns TRUE if the function returns true for each item.

*filter (): Each item of an array runs the given function, and returns a list of the items that the function returns True.

*foreach (): each item of an array runs the given function , with no return value.

*map (): Each item of an array runs the given function, and returns a list of the results of each invocation.

*some (): each item of an array runs the given function if the function returns true for any one of the items. The function returns True.

Note: All methods do not affect the value of the array.

where every () and some () are the most similar. is used to query whether an array of items satisfies a condition. Returns true if all is satisfied. Every () returns true only if one item returns TRUE. Some () will return true.

varnumbers=[1,2,3,4,5,4,3,2,1];varEveryresult=numbers.every (function(Item,index,array) {returnItem>2}) Console.log (Everyresult);varSomeresult=numbers.some (function(Item,index,array) {returnItem>2}) Console.log (Someresult)varFilterresult=numbers.filter (function(Item,index,array) {returnItem>2}) Console.log (Filterresult)varMapresult=numbers.map (function(Item,index,array) {returnItem*2}) Console.log (Mapresult)//The ForEach method does not return a value. You can take advantage of each item in the array to perform some actionsNumbers.foreach (function(Item,index,array) {if(item>3) Console.log (' This number is > 3. ')  Else if(item<3) Console.log (' This number is < 3. ') ElseConsole.log (' This number is = 3. ')})

The results are as follows:

* Merge Arrays

ECMAScript 5 adds two merge methods: Reduce () and reduceright (). Both of these methods iterate over all the items of an algebraic group and then build a final return value. Reduce () iterates from the first item of the array to the end. and Reduceright () is a forward traversal from the last item.

var numbers=[1,2,3,4,5,4,3,2,1]; var sum=numbers.reduce (function(pre,cur,index,array) {return pre+cur}) Console.log ( sum);   //  - var sum2=numbers.reduceright (function(pre,cur,index,array) {return pre+cur}) Console.log (sum2)   //

Using these two methods depends primarily on which header you want to traverse the array from, except that they are identical.

JavaScript Learning--array 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.