All operations of the JS array

Source: Internet
Author: User
Tags array length

JS has a lot of array operations, here is a common and infrequently used array operation methods.

First, the creation of arrays

There are two ways to create an array, one through the literal and the other through the array constructor.

1. Literal

var = [NUM1];

It is important to note that when you create an array by using the literal, you cannot add "," in the last array element, because a bug will appear in the older version of the browser. As in the following example, in Num2, you create an array that contains 1,2,3,undefined four items or three items with a three-to-one.

var num2 = [1,2,3,];//non-recommended notation

2.Array Constructors

var New Array ();//Empty array

Array () can receive the containing item as an argument, and a valarray containing the incoming item, such as NUM4, is created.

You can also receive a number as a parameter, and an array with an array length of that number, such as NUM5, is created.

var New Array ("1", "2", "3");//equivalent to ["1", "2", "3"]varnew Array (3),//length to 3, elements are undefined arrays

Second, the conversion of the array

For the conversion of arrays, here are just two ways to convert an array into a string. are ToString () and join (), respectively.

1.toString ()

The method returns a comma-separated string of items in the array. The ToString () method is implicitly called when an array is printed using the alert (array) method.

var = [Num6]; var num6str = num6.tostring (); // "NUM6"alert (a); // " the"

2.join ()

Join () receives only one parameter, which is the concatenation of the strings in the array, and, if not, the default is "," as the delimiter, the effect is equivalent to the ToString () method.

var num7 = [];num7.join ("$"); // "1$2$3"num7.join (); // " the"

Three, Stack method

Stacks are a first-in-class data structure, and the array provides a push () and Pop () method that resembles the behavior of a stack, so called a stack method.

1.push ()

The push () method can receive multiple parameters, add them sequentially to the end of the array, and return the modified array length.

var = [Num8]; var num8length = Num8.push (4,5); alert (NUM8); // 1,2,3,4,5alert (num8length); // 5

2.pop ()

The Pop () method removes the last item of the array and returns the removed item.

var = [Num9]; var last = Num9.pop (); // 3

Iv. Queue method

  1.shift ()

The shift () method removes the first item from the array and returns the removed item.

var = [Num10]; var first = Num10.shift (); // 1

2.unshift ()

The Unshift () method, in contrast to the shift () method, can receive multiple parameters, add the parameters to the front end of the array in turn, and return the length of the modified array.

var = [Num11]; var addarray = Num11.unshift ("1", "0"); // 5

Five, re-order method

1.reverse ()

The reverse () method reverses the items in the array and returns the sorted array.

var num12 = [];num12.reverse (); // [3,2,1]

2.sort ()

The sort () method is by default sorted alphabetically by ASCII code. When you use the sort () method, the ToString () method is implicitly called to convert each item in the array into a string conversion, in effect, to sort the string ASCII and return the sorted array.

For data of type number in array items, we can pass in a comparison function in sort (), which receives two parameters, the first parameter is the previous one, and the second argument is the latter. Compare the two parameters, if the return value is >0, the two contrast items are swapped, the position is swapped, and the previous item is compared, and so on until the return value is returned to 0 or <0.

In the comparison function, return value >0, array item swap position, return value <0, array item does not swap position; return value = 0, meaning two items are equal, array item does not swap position.

var num13 = [3,2,7,14,111,0];num13.sort (function(value1,value2) {      return value1-value2;}); alert (NUM13); // 0,2,3,7,14,111

Vi. Methods of operation

  1.concat ()

The Concat () method is to concatenate an array with an array or add an array item to the end of the array.

Concat () Creates a copy of the current array and then adds the received parameters to the end of the copy in turn. If no parameters are passed in, a copy of the current array is returned, which is equivalent to the copy of the array, and if one or more of the array parameters are passed in, each item in the arrays parameter is added sequentially at the end of the copy, and the values are added to the end of the copy, in turn, if they are passed to one or more non-

Note: the concat () method can be used to return the attributes of a new array for copying the array.

var = [Num14]; var num15 = Num14.concat ([4,5],[6,7]); Alert ("when the parameter is multiple arrays:" +NUM15); // 1,2,3,4,5,6,7 var num16 = num14.concat (4,5); Alert ("when the parameter is non-array:" +NUM16); // 1,2,3,4,5

2.slice ()

Slice () can create a new array based on one or more items in the current array, and return a new array.

Slice () can receive one or two parameters, that is, the starting and ending positions of the item to be returned. When there is only one argument, it returns from the position specified by the parameter to the end of the array, and when the two arguments are passed, an array item is returned from the starting position to the previous item in the ending position.

Note: The slice (0) method can be used to return the attributes of a new array for copying the array.

var num17 = [];num17.slice (1); // [2,3]num17.slice; // [2]

3.splice ()

The splice () method is a powerful way to manipulate arrays. Because this method can be used to delete, insert, and replace operations on arrays.

Delete: Splice (index,number), only need to pass in two parameters, index is the first position to delete, number is deleted.

Insert: Splice (index,0,value1,value2,...) requires at least three parameters to be passed in, index to insert value1,value2 from position Index ....

Replacement: Splice (Index,number,value1,value2 ...) requires at least three parameters to be passed in, index is the position to begin replacing, number is the replacement item, Value1,value2, and so on.

Return value: The Splice () method returns an array that is always returned, and if there is a delete item, returns an array containing all the deleted items, and returns an empty array if no items are deleted.

var = [Num18]; // Delete operation Num18.splice (0,2); // return [Num18], at this time = [3] // insert Operation Num18.splice (1,0,4,5,6); // return [], at this time Num18 =[3,4,5,6] // Replacement Operation Num18.splice (2,2,3,3); // return [5,6], at this time num18 = [3,4,3,3]

Vii. Position method

  The location method contains two methods, IndexOf () and LastIndexOf (), two methods receive two parameters, the first parameter is a lookup item, the second parameter (optional) is the starting position of the lookup, returns the first position where the lookup item appears, and returns 1 if no found. When you compare a lookup item to each item in the array, use the congruent operator = = =, which requires the same value as the data type.

1.indexOf ()

IndexOf (value) The method is to look for an item of value from the beginning of the array.

IndexOf (Value,index) The method is to start looking for an item with a value of values from an item that is subscript index.

var num19 = [];num19.indexof (1); // returns 0num19.indexof (3,1); // returns 2

2.lastIndexOf ()

LastIndexOf (value) The method is to look for an item of value from the end of the array.

LastIndexOf (Value,index) This method is the entry starting at the end of the array (starting at 0) of index and looking for an item with value values beginning at the beginning of the array.

var num20 = [];num20.lastindexof (1); // return 0num20.lastindexof (n); // returns 0

Eight, iterative method

1.every ()

Every (function (Item,index,array) {reutrn ...;}) Each entry of an array is passed in to the given function, which returns TRUE if the function evaluates to every item, otherwise false. (Similar and operator)

var = [Num21]; var every = Num21.every (function(item,index,array) {    return (item>0) ;}); // true var every1 = Num21.every (function(item,index,array) {    return (item >2)}); // false

2.some ()

Some (function (Item,index,array) {return ...}) Each entry of an array is passed into the given function, which returns TRUE if the function returned true for an item, otherwise false. (similar or operator)

var = [Num22]; var some= num21.some (function(item,index,array) {    return (item>2);}); // true var some1= num22.some (function(item,index,array) {    return (item >6)}); // false

3.forEach ()

The ForEach (function (Item,index,array) {}) is passed into the given function for each item of the array, with no return value. (like for Loop)

var num23 = [];num23.foreach(function(item,index,array) {    Console.log (item );});

4.map ()

The map (function (Item,index,array) {}) is passed into the given function for each item of the array, and the return value is the array after the arrays operation.

var num24 = [];num24.map(function(item,index,array)    {return item+2;}); // [3,4,5]

5.filter ()

The filter (function (Item,index,array) {}) is passed into the given function for each item of the array, and the return value is an array of the items returned by the given function as true.

var num25 = [];num25.filter(function(item,index,array)    {return (Item>2);}); // [3]

Nine, Merge method

There are two merge methods, reduce () and reduceright () respectively. The two methods receive two parameters, respectively, for the given function and the pre initial value (optional). Each of the iterated algebraic groups is passed into the given function, and a final return value is constructed.

1.reduce ()

Reduce (function (Pre,cur,index,array) {return ...}) Starting with the first item, when iterating, the value returned by the given function is given as the pre parameter to the next iteration until the end. Cur refers to the current item, index is the current item subscript, and array is the call.

var num26 = [1,2,3];
Pass only the given function num26.reduce (function (Pre,cur,index,array) {return pre+cur;}); // 6
Passing in the given function and pre initial values
Num26.reduce (function (pre,cur,index,array) {    return pre+cur;},4);//10

2.reduceRight ()

The Reduceright () and reduce () methods are all the same except from the end of the array or from the beginning of the traversal. Reduceright () is traversed from the end of the array.

All operations of the JS array

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.