Summary of array type methods in JavaScript

Source: Internet
Author: User

The array type is one of the most commonly used types in ECMAScript, and the arrays in ECMAScript are quite different from those in most other languages. Each item of the ECMAScript array can hold any type of data. Most of the methods of array types are summarized here, which makes it easier to find them later.

First, the basic way to create an array

There are two basic ways to create data:

1. Using the array constructor

var colors=New Array ();
var colors=new Array (20); Create an array with a length value of 20
var colors=new Array ("Red", "blue"); Create an array containing 2 strings worth

2. Using array literals notation

var colors=[]; var colors=["Red", "blue";

Second, reading and setting array values

var colors=["Red", "Blue", "Green"];alert (colors[0]); Read the first item
Colors[2]= "BLACK"; Modify the third item
Colors[3]= "Brown"; Add Item Fourth
colors.length=2; Delete all values after the second item
colors[colors.length]= "Yellow"; Add a new item at the end of the array

Note: The length property of an array is not read-only. You can therefore set this property to remove an item from the end of the array or to add a new item to the array.

Third, the detection array

if (Array.isarray (value)) {    //user Action}

Iv. Method of conversion

var colors=["Red", "Blue", "Green"];alert (Colors.tostring ()); Red,blue,green
Alert (colors.valueof ()); Red,blue,green

All objects have the ToString () and valueof () methods. Calling the ToString () method returns a comma-delimited string that is stitched together by each of the strings in the array. ValueOf () returns an array. The ToString () method of an array can be substituted with the join () method. However, the join () method can customize the delimiter

var colors=["Red", "blue";
Alert (Colors.join (",")); Red,blue
Alert (Colors.join ("| |)"); red| | Blue

Five, Stack method

The stack is a LIFO last-in-first-out data structure, that is, the most recently added item was first removed. Use the push () and Pop () methods to implement a stack-like behavior.

The push () method can receive any number of arguments, add them to the end of the array one by one, and return the length of the modified array.

The Pop () method removes the last item from the end of the data, reduces the length value of the array, and then returns the item that was removed.

var colors=New  Array ();  var count=colors.push ("Red", "Blue"); alert (count);  2var item=Colors.pop ();  alert (item);  Bluealert (colors.length); 1

Vi. Queue Methods

The access rules for queue data structures are FIFO first-out structures. The queue adds items at the end of the list, removing items from the front end of the list. Use the push () and shift () methods to implement a queue-like behavior.

The shift () method moves the first item in the array and returns the item, minus 1 of the length.

var colors=New Array ();
var Count=colors.push ("Red", "blue");
alert (count); 2
var item=colors.shift ();
alert (item); Red
alert (colors.length); 1

Note: Ecamscript also provides a unshift () method. It is the opposite of shift use: It can add any item in front of the array and return the length of the new array. Using the Unshift () and Pop () methods, you can simulate the queue in the opposite direction, adding items to the front of the array, removing items from the end of the data. (no longer an example).

Seven, reorder method

1. Reverse array order reverse ()

var arr=[1,2,3,4,5];arr.reverse (); alert (arr); 5,4,3,2,1

2. Sorting method Sort ()

Sort () In most cases, a comparison function is received as a parameter so that we specify which value is in front of which one is worth.

function Compare (v1,v2) {    return v2-v1;}
var arr=[0,1,5,10,15];
Arr.sort ();
Alert (arr); 0,1,10,15,5 is not the sort result we want
Arr.sort (Compare);
Alert (arr); The result of 0,1,5,10,15 hope

Eight, Operation method

1.concat ()

The Concat () method creates a new array based on all the items in the current array, which first creates a copy of the current data and then adds the received parameters to the end of the copy.

var arr=[1,2];  var arr2=arr.concat (3,[4,5]); alert (arr);  1,2alert (ARR2); 1,2,3,4,5

2.slice ()

The slice () method can create a new array based on one or more items in the current array. It can receive one or two parameters, that is, to return the starting and ending positions of an item (excluding the end position). A parameter returns all items at the specified position to the end of the current array.

var arr=[1,2,3,4,5]; var arr2=arr.slice (1); var arr3=arr.slice (1,4); alert (ARR2);    2,3,4,5alert (ARR3); 2,3,4

Note: If the argument is a negative value, use the array length plus the number to determine the corresponding position. For example Slice ( -2,-1) and slice (3,4) get the same. If the end position is less than the start position, an empty array is returned.

3.splice ()

The main purpose of the splice () method is to insert an item into the middle of the array.

Splice (0,2)//delete the first two entries in the array (the first parameter is the position where the first item is to be deleted, the second parameter is the number of items to be deleted)
Splice (2,0, "Red", "blue")//Insert "red" and "blue" starting at position 2 of the current array (the first second parameter is the same as above, and the third and later represents the item to be inserted)
Splice (2,1, "Red", "blue")//delete the entry for position 2 from the current array, and then insert "red" and "blue" starting at position 2

Nine, location method

IndexOf () and LastIndexOf (). They all receive two parameters: the index of the item to find and the location that represents the start of the lookup (the second parameter is optional).

var arr=[1,2,3,4,5,4,3,2,1];alert (Arr.indexof (4)); 3
Alert (Arr.lastindexof (4)); 5
Alert (Arr.indexof (bis)); 5
Alert (Arr.lastindexof (bis)); 3

Ten, Iterative methods

Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.

var numbers=[1,2,3,4,5,4,3,2,1]; var everyresult=numbers.every (function (Item,index,arry) {//Parameter description: The value of the array item, the position of the item in the array, the array object itself
return (ITEM>2);
});
alert (Everyresult); False

Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.

var numbers=[1,2,3,4,5,4,3,2,1]; var someresult=numbers.some (function// parameter Description: The value of the array item, the position of the item in the array, the return of the array object itself  (Item>2);});  alert (Someresult);  //true  

Filter (): Each item in an array runs the given function, and returns a list of items that are true of the function.

var numbers=[1,2,3,4,5,4,3,2,1]; var filterresult=numbers.filter (function// parameter Description: The value of the array item, the position of the item in the array, the array object itself  Return (Item>2);});  alert (Filterresult);  //[3,4,5,4,3]  

Map (): Each item in the array runs the given function, returning an array that consists of the results of each function call.

var numbers=[1,2,3,4,5,4,3,2,1]; var mapresult=numbers.map (function// parameter Description: The value of the array item, the position of the item in the array, the return of the array object itself  item*2;});  alert (Mapresult);  //[2,4,6,8,10,8,6,4,2]  

ForEach (): Runs the given function for each item in the array, with no return value.

var numbers=[1,2,3,4,5,4,3,2,1]; Numbers.foreach (function// parameter Description: The value of the array item, the position of the item in the array, the array object itself //user action });
  

Xi. method of merging

ECMAScript5 two new merge methods. Reduce () and reduceright (). Both methods iterate over all the items in an algebraic group. The difference is that the reduce () method starts with the first item in the array, and Reduceright () starts with the most of the array. Both methods receive two parameters: a function called on each item, and an initial value (optional) that is the base of the merge.

var values=[1,2,3,4,5]; var sum=value.reduce (function(prev,cur,inex,array) {//Parameter description: Previous value, current value, index of item, array object    return prev+cur;});
alert (sum); 15

var sum2=values.reduce (function (Prev,cur,index,arry) {
return prev+cur;
},20);
alert (SUM2); 35

Thanks for reading.

Summary of array type methods in JavaScript

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.