JS reference type (2)--array type

Source: Internet
Author: User
Tags deprecated

"2" Array type
Each item of the ECMAScript array can hold any type of data, and the size can be dynamically adjusted, which can automatically grow as the data is added to accommodate the new data.

(1) Creating an array

1 "Using the array constructor

var New Array (); var New Array (a); var New Array ("Red", "Blue", "green"); var colors = Array (3); var colors = Array ("Greg");

2 "Using array literals

var colors = ["Red", "Blue", "green"]; var colors = []; var colors = [1, 2,]; // Deprecated , creates an array with 2 or 3 items var colors = [,,,,,]; // Deprecated , creates an array with 5 or 6 items

As with objects, the array constructor is not called when you use the literal notation.

(2) Array Length property

The length property of an array is not just readable. By setting this property, you can remove an item from the end of the array or add a new item to the array.

 var  colors = ["Red", "Blue", "green"  = 2; //  Remove the last  alert (colors[2]); // undefined  var  colors = ["Red", "Blue", "green"  = 4; //  alert (colors[4]); // undefined  var  colors = ["Red", "Blue", "green" ];colors[ Colors.length]  = "BLACK"; //  add a color at position 3  colors[colors.length] = "Brown"; //  add a color at position 4  
(3) Detecting arrays

1 instanceof Operator: Determines if an object is not an array

if instanceof Array) {// to perform certain actions on an array}

2 "Array.isarray () method: Determine if a value is an array

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

This method is supported by IE + + and other browsers.

(4) Conversion method

1 The previous article mentions that object objects have tolocalstring (), toString (), and valueOf () methods

    • toLocaleString () Method: Returns the string representation of an object that corresponds to the region of the execution environment.
    • ToString () Method: Returns the string representation of an object.
    • ValueOf () Method: Returns the original value of the object, possibly a string, numeric, or Boolean value, and so on. Usually the same as the return value of the ToString () method.

In the case of arrays:

    • ToString () Method: Returns a comma-delimited string that is stitched together as a string of each value in the array.
    • ValueOf () Method: Returns the original value of the object.
varcolors = ["Red", "Blue", "green"];console.log (colors.tostring ()); //Red,blue,greenConsole.log (Colors.tolocalstring ());//Red,blue,greenConsole.log (Colors.valueof ());//["Red", "Blue", "green"]Console.log (colors);//["Red", "Blue", "green"]Alert (colors.tostring ());//Red,blue,greenAlert (colors.tolocalstring ());//Red,blue,greenAlert (colors.valueof ());//Red,blue,greenalert (colors);//Red,blue,green

Alert () takes a string argument, so the ToString () method is called in the background.
2 Join () method: Use a different delimiter to construct a string containing all array items

var colors = ["Red", "Blue", "Green"];alert (Colors.join (//red,blue,green   red| | blue| | Green

If you do not pass any value to the join method or pass it to undefined, use a comma as the delimiter.
If the value of an item in the array is null or undefined, the value is represented as an empty string in the result returned by the join (), tolocalstring (), toString (), ValueOf () methods.

(5) Stack method: LIFO LIFO; insert in top of stack, remove

1 "Push () method: You can accept any number of parameters, add them to the end of the array one by one, and return the length of the modified array.
2 Pop () 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.

var New Array (); var count = Colors.push ("Red", "green"//2= Colors.push ("Blue"  // 3 var item =//"Blue"//2
(6) Queue method: FIFO first-out; the queue adds items at the end of the list, removing items from the front end of the list

1 "Push () method: You can accept any number of parameters, add them to the end of the array one by one, and return the length of the modified array.
2 Shift () method: Removes the first item in the array and returns the item, minus 1 of the length.

var New Array (); var count = Colors.push ("Red", "green"//2= Colors.push ("Blue"  // 3 var item =//"Red"//2

3 Unshift () method: Add any item in the front of the array and return the length of the new array.

Using the Unshift () and Pop () methods, you can simulate a queue in the opposite direction, that is, adding items to the front of the array, removing items from the end of the array.

var New Array (); var count = Colors.unshift ("Red", "green"//2= Colors.unshift ("Blue"  //3//["Blue", "Red", "green"]var item =  // "Green" // 2
(7) Reorder method

1 reverse () method: Reverses the order of the array items.

var values = [1,2,3,4,5//[5,4,3,2,1]

2 sort () method: Arranges array items in ascending order.

var values = [0,1,5,10,15,6,25//[0,1,10,15,25,5,6] for string comparison

The sort () method can accept a comparison function as a parameter.

functionCompare1 (value1,value2) {if(value1<value2) {return-1;}Else if(value1>value2) {return1;}Else{return0;}}functionCompare2 (value1,value2) {if(value1>value2) {return-1;}Else if(value1<value2) {return1;}Else{return0;}}functionCompare (value1,value2) {returnValue2-value1;}varvalues = [0,1,5,10,15,6,25];values.sort (Compare1); //[0,1,5,6,10,15,25]Values.sort (Compare2);//[25,15,10,6,5,1,0]Values.sort (Compare);//[25,15,10,6,5,1,0]
(8) Operation method

1 "concat () Method: Creates a new array based on all the items in the current array. does not affect the original array.

var colors = ["Red", "green", "Black"]; var colors2 = Colors.concat ("Yellow", ["Blue", "Brown"//red,green,black//  Red,green,black,yellow,blue,brown

2 "Slice () method: Creates a new array based on one or more items in the current array. does not affect the original array.
You can accept one or two parameters, that is, to return the start and end positions of an item.

 var  colors = ["Red", "green", "black", "yellow", "blue", "Brown" ]; var  colors2 = Colors.slice (1 var  colors3 = Colors.slice (1,4 // red,green,black,yellow,blue,brown  alert (COLORS2); // green,black,yellow,blue,brown  alert (COLORS3); // green,black,yellow  

If the slice () method has a negative number in its argument, the array length is used to determine the corresponding position. If the end position is less than the start position, an empty array is returned.
3 "Splice () method.
Delete: You can delete any number of items by specifying only 2 parameters: the location of the first item to delete and the number of items to delete.
Insert: You can insert any number of items to a specified location, providing only 3 parameters: Start position, 0 (number of items to delete), item to insert. If you want to insert more than one item, you can pass in four, five, or any number of items.
Replace: You can insert any number of items at 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.
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).

varcolors = ["Red", "green", "blue"];varremoved = Colors.splice (0,1); alert (colors); //Green,bluealert (removed);//Redremoved= Colors.splice (1,0, "Yellow", "orange"); alert (colors); //Green,yellow,orange,bluealert (removed);//an empty array is returned.removed= Colors.splice ("Red", "purple"); alert (colors); //Green,red,purple,orange,bluealert (removed);//Yellow
(9) Location method

Two methods of IndexOf () and LastIndexOf (). All receive two parameters: the item to find and an index that represents the location of the lookup start (optional). where the IndexOf () method looks backwards from the beginning of the array, the LastIndexOf () method looks forward from the end of the array.
Both methods return the position of the item being looked up in the array, or 1 if it is not found. When comparing the first argument to each item in the array, the strict equality operator is used, that is, the items that are required to find must be strictly equal.

varnumbers = [1,2,3,4,5,4,3,2,1];alert (Numbers.indexof (4));//3Alert (Numbers.lastindexof (4));//5alert (Numbers.indexof ((bis));//5Alert (Numbers.lastindexof (bis));//3varperson = {Name: "Nicholas"};varPeople = [{name: ' Nicholas '}];varMorepeople =[Person];alert (People.indexof (person));//-1Alert (Morepeople.indexof (person));//0
(10) Iterative method

ECMASCRIPT5 defines 5 iterative methods for an array.
Each method accepts two parameters: the function to run on each item and, optionally, the scope object that runs the function-the value that affects this.
The functions passed in these methods receive three parameters: the value of the array item, the position of the item in the array, and the group object itself.

    • Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.
    • Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.
    • Filter (): Each item in an array runs the given function, and returns a list of items that are true of the function.
    • ForEach (): Runs the given function for each item in the array, and the method does not return a value.
    • Map (): Each item in the array runs the given function, returning an array that consists of the results of each function call.

None of the above methods will modify the contained values in the array.

varnumbers = [1,2,3,4,5,4,3,2,1];varEveryresult = Numbers.every (function(Item,index,array) {return(item>2);}); alert (Everyresult); //falsevarSomeresult = Numbers.some (function(Item,index,array) {return(item>2);}); alert (Someresult); //truevarFilterresult = Numbers.filter (function(Item,index,array) {return(item>2);}); alert (Filterresult); //[3,4,5,4,3]varMapresult = Numbers.map (function(Item,index,array) {returnItem*2;}); alert (Mapresult); //[2,4,6,8,10,8,6,4,2]varForeachresult = Numbers.foreach (function(Item,index,array) {//perform certain actions});//similar to For loop

IE + + and other browser support

(11) Merge method

The reduce () and Reduceright () methods iterate over all the items of an algebraic group, and then build a value that is ultimately returned.
where reduce () starts from the first item in the array and traverses through to the end. The Reduceright () method is the opposite.
Both methods accept two parameters: a function that is called on each item and (optionally) the initial value that is the base of the merge.
The functions passed in these methods receive four parameters: the previous value, the current value, the index of the item, and the array object.

var values = [1,2,3,4,5]; var sum = values.reduce (function(prev,cur,index,array) {return prev+  //  the

IE + + and other browser support

JS reference type (2)--array type

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.