On common methods of array operation in JavaScript

Source: Internet
Author: User
Tags javascript array

Common methods for array manipulation in JavaScript 1. Detecting arrays

1) detects if the object is an array, using the instanceof operator

if (value instanceof Array) {// perform certain actions on array}

2) Gets the type of the object, compares whether it is an object type (this method can only detect if it is an object, not recommended)

if (typeof(value) = ="Object") {// to perform certain operations on an array}

3) detects if the object is an array, using the Array.isarray () method (only Ie9+,firefox 4+,safari 5+,opera 10.5+ and Chrome are supported)

if (Array.isarray (value)) {// to perform certain operations on an array}
2. Conversion method

All objects have tolocalestring (), toString (), and valueof () methods.

The ToString () method of the call array returns a comma-delimited string that is stitched together as a string of each value in the array.

The return or array of the call valueof ().

Join () method : Receives a parameter, which is a string used as a delimiter, and then returns a string containing all the array items

var colors=["Red", "green", "Blue"];alert (Colors.join ("| |)"); // red| | green| | Blue
3. Stack method

The stack is a LIFO (Last-in-first-out, LIFO) data structure.

The JavaScript array specifically provides the push () and Pop Method () methods to implement a stack-like behavior

1):p the Ush () method can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array

2):p the OP () method removes the last item from the end of the array, reduces the length value of the array, and then returns the item that was removed.

varcolors=NewArray ();//Create an arrayvarCount=colors.push ("Red", "green");//push in two itemsalert (count);//2Count=colors.push ("Black");//push into another itemalert (count);//3varItem=colors.pop ();//removes the last item and returns the value of the last itemalert (item);//"BLACK"alert (colors.length);//2


The above code first uses push () to push two strings to the end of the array and saves the returned result in the variable count. Then a value is pushed, and the result is saved in count. Because the array contains 3 items, push () returns 3.
When a pop () is called, it returns the last item in the array, the string "Black". Thereafter, only two items are left in the array.
4. Queue method

The access rules for the stack data structure are LIFO (Last-in-first-out, LIFO), while the access rules for the queue data structures are FIFO (first-in-first-out, first-in, FIFO).

The queue adds items at the end of the list, removing items from the front end of the list.

JavaScript provides the shift () and Unshift () methods for the queue

1): Shift () moves the first item in the array and returns the change, minus 1 of the length.

2): Unshift () adds any item to the front of the array and returns the length of the new array.

Combining the push () and pop methods, one instance of the shift () and Unshift () methods

varn=NewArray ("Zhang San", "John Doe"); N.push ("Harry");//Add a parameter to the end of the array and modify the array lengthN.shift ();//removes the first item of an array and returns the itemN.unshift ("Penny");//adding parameters to the array front endN.pop ();//removes the last item from the end of the array                        //loop Displays the values of the array             for(vari=0;i<n.length;i++) {Console.log (n[i]); }
//Penny John Doe 
5. Reorder Methods

There are already two methods in the array that can be used for reordering directly: reverse () and sort ()

By default, the sort () method sorts the array items back in ascending order-that is, the smallest value is first, the largest is the last, and in order to implement the sort, the sort () method invokes the ToString () transformation method of each array item.

Then compare the resulting strings to determine how to sort. That is, each item in the array is a numeric value, and the sort () method compares the string as follows

    var values=[0,1,5,10,15];            Values.sort (); // to sort the display            alert (values); // 0,1,10,15,5

The sort () method changes the original order based on the result of the test string. Because the array 5 is light rain 10, but when the string comparison, "10" is located in front of "5", so the order of the array is modified. This sort is not the best scenario in many cases, so sort () The method can receive a comparison function as a parameter so that we define which value is in front of which value.

The comparison function receives two parameters, returns a negative number if the first argument precedes the second one, and returns 0 if the two arguments are equal, and returns a positive number if the first argument is after the second. Here is a simple comparison function:


functionCompare (value1,value2) {if(value1<value2) { return-1; }Else if(value1==value2) { return0; }Else { return1; } } varvalues=[0,1,5,10,15]; Values.sort (compare);//to sort the displayalert (values);//0,1,5,10,15

After the comparison function is passed to the sort () method, the values remain in the correct ascending order. Of course, you can also produce a descending sort result by comparing functions, as long as the return value of the comparison function is exchanged.

Note: Value1<value2 returns 1 for positive order, return 1 for reverse

Of course, if you reverse the original order of the array, using the reverse () method is faster

Of course. For numeric types or their valuesof () methods, you can use a simpler comparison function, which returns an object type of numeric type. This function simply minus the second value with the first value

function Compare (value1,value2) {return value1-value2;}
This method returns a positive sequence
6. How to Operate

1): The Concat () method can create a new array based on all the items in the current array.

Without passing arguments to the concat () method, it simply copies the current array and returns a copy. How to pass to the concat () method is one or more arrays,

The method adds each item in these arrays to the result array. If the value passed is not an array, the values are simply added to the end of the result array. Look at a column below

var colors=["Red", "green", "Blue";             var color2=colors.concat ("Yellow", ["Black", "Brown"]);            alert (COLOR2); // Red,green,blue,yellow,black,brown

2): The Slice () method creates a new array based on one or more items in the current array.

The slice () method can receive one or two parameters, that is, the starting and ending positions to return.

In the case of only one argument, the slice () method returns all items starting at the specified position of the parameter to the end of the current array.

How to have two parameters, the method returns the item between the start and end positions--but not the end position. The slice () method does not affect the original array, and a column

var colors=["Red", "green", "blue", "yellow", "black"];            Colors.split (1); // Green,blue,yellow,black            Colors.split (1,4)//Green,blue,yellow

3): Splice () method is probably the most powerful array method, it has many kinds of usage.

The main purpose of splice () is to insert items into the middle of the array, but there are 3 ways to use this method

A: 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.

Columns such as: Splice (0,2) Delete the first two items in the array.

B: Insert: You can insert any number of items to the specified location, providing only 3 parameters: Start position, 0 (number of items to delete), and items to insert.

How to insert multiple items, you can pass in the four, five, and even any number of items.

Columns such as: Splice (2,0, "Red", "green") Insert the string "red" and "green" starting at position 2 of the current array

C: Replace: You can insert any number of items to the specified location, and delete any number of items at the same time, providing only 3 parameters: The starting position, the number of items to delete, and any number of items to insert.

The number of items inserted does not have to be equal to the number of items deleted.

Columns such as: Splice (2,1, "Red", "green") delete the current array position 2, and then insert the string "red" and "green" from position 2

Note: The insertion and substitution method is the same, the difference is the 2nd parameter, 0 means that the insert is not deleted, greater than 0 indicates the number to be deleted

The splice () method always returns an array that contains the items that were deleted from the original array (an empty array is returned if no items were deleted).


Here is a list of the above 3 splice () method, as follows:

varcolors=["Red", "green", "blue"]; varRemoved=colors.splice (0,1);//Delete First itemalert (colors);//Green,bluealert (removed);//Red, there is only one item in the returned arrayremoved=colors.splice (1,0, "Yellow", "orange");//Insert 2 Data starting from position 1alert (colors);//Green,blue,yellow,orangealert (removed);//returns an empty arrayremoved=colors.splice ("Red", "purple");//Insert 2 data from position 1 and delete the data for position 1alert (colors);//Green,red,purple,yellow,orangealert (removed);//Yellow, the returned array contains only one item

7. Location method

Two location methods: IndexOf () and LastIndexOf (), both of which receive two parameters: the subparagraphs to find (optional) represents the index to find the seven-point position.

1) indexOf (): Looks backwards from the beginning of the array (position 0)

2) lastIndexOf (): Looking forward from the end of the array

Both methods return the position of the found item in the array, or return-1 if not found.

When comparing the first argument to each item in the array, the strict equality operator is used, that is, the items required for the lookup must be strictly equal

Here are some examples of these 2 methods, as follows:

varnumbers=[1,2,3,4,5,4,3,2,1]; Alert (Numbers.indexof (4));//3 Returns the first occurrence of the 4 positionAlert (Numbers.lastindexof (4));//5 Returns the last occurrence of the 4 positionAlert (Numbers.indexof (bis));//5 Find the position where the first 4 appears, starting from position 4Alert (Numbers.lastindexof (bis));//3 Find where the last 4 appears from position 4                                    varPerson={name: "ToNi"}; varPeople=[{name: "ToNi"}]; varmorepeople=[person]; Alert (People.indexof (person));//return-1 must be strictly equal, not just value equalAlert (Morepeople.indexof (person));//returns 0

This post is a reference to JavaScript advanced programming books

I read the book after the collation and some of my own understanding, need to be able to help everyone, thank you

On common methods of array operation in JavaScript

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.