(Fifth day) array

Source: Internet
Author: User
Tags javascript array

Concept

An array is an ordered collection of values. Each value is called an element, and each element has a position in the array, represented by a number, called an index.

Creating an array (1) using an array of direct amounts is the simplest way to create an array, separating the array elements with commas in square brackets.
1 varempty = [];//an array with no elements2 3 varprimes= [2,3,5,7, One] ;//array with 5 values4 5 varMisc = [1.1,true,"a"];//3 different types of elements and the end of a comma

The values in the array's direct quantities are not necessarily constants; they can be arbitrary expressions:

1 var Base 1024x768 ; 2 3 var table = [basebase+1base+2base+3 ];

If you omit a value from the array's direct amount, the omitted element is given the undefined value:

1 var count = [1,3];  // The array has three elements, and the middle element has a value of undifined 2 3 var undefs = [,,];   // The array has two elements, all of which are undifined
(2) through the constructor array () is another way to create an array. Constructors can be called in three ways. (1) No arguments at call
1 var New Array ();

The method creates an empty array without any elements, equivalent to the array direct amount [].

(2) A numeric parameter is called when it specifies the length
1 var New Array (ten);

This technique creates an array of the specified length. This form of array () constructor can be used to pre-allocate an array space when the required number of elements is known beforehand. Note that there are no stored values in the array, even the indexed properties of the array "0", "1" and so forth are undefined.

(3) displays a non-numeric element that specifies two or more array elements or arrays
1 var New Array (54321"testing, testing" );

"Note" In fact, the array index is only a special type of object property name, which means that the JavaScript array does not have the concept of "out of Bounds" errors. When attempting to query a property that does not exist in any object, it will not give an error, only the undefined value. Similar to objects, this is also true for objects.

Sparse array

A sparse array is an array of non-contiguous indexes that begin with 0. Typically, the value of the length property of an array represents the number of elements in the array. If the array is sparse, the length property value is greater than the number of elements. You can create a sparse array by using the array () constructor or simply specifying that the index value of the array is greater than the current array length.

1 New Array (5);   // the array has no elements, but A.length is 5 2 3 a = [];                   // create an empty array, length = 0; 4 5 a[0;       // an assignment adds an element, but sets the length to 1001

Note: Sparse arrays are not created when values are omitted from the array's direct amount. The omitted element is present in the array and its value is undefined. There are some subtle differences between these and the array elements that do not exist at all. You can use the in operator to detect the difference between the two:

1 vara1 = [,,,];//array is [undefined, undefined, undefined]2 3 varA2 =NewArray (3);//There are no elements in the array4 5 0 inchA1//= = True:a1 has an element at index 06 7 8 0 inchA2//= = FALSE:A2 no element at index 0
Common methods for arrays

Methods in the ECMASCRIPT3

(1) Join ()

The Array.join () method converts all the elements in an array into strings and stitching them together, returning the last generated string. You can specify an optional string in the generated string to separate the elements of the array. If you do not specify a delimiter, commas are used by default. As shown in the following code:

1 varA = [1,2,3];//create an array with three elements2 3A.join ();//= "1, 2, 3"4 5A.join ("")//= "123"6 7 varb =NewArray (Ten);//An empty array of length 108 9B.join ("-");//= "---------": a string of 9 hyphens

The Array.join () method is the inverse of the String.Split () method, which splits the string into blocks to create an array.

(2) Reverse ()

The Array.reverse () method reverses the order of the elements in the array, returning an array of reverse. It takes a substitution; in other words, it does not create new arrays by rearranging the elements, but instead rearranges them in the original array.

1 var a = [123]23 a.reverse (). Join ()   // = = "3, 2, 1", and now A is [3, 2, 1]
(3) sort ()

The Array.Sort () method sorts the elements in the array and returns the sorted array. When sort () is called without parameters, the array is sorted alphabetically (if necessary, a temporary conversion string is compared)

var New Array (banana""Cherry"" Apple"); A.sort (); var s = a.join ("");   // s = = "Apple, banana, cherry"

"Note" If the array contains undifined elements, they will be queued to the end of the array

In order to sort the array in other ways rather than alphabetically, you must pass a comparison function to the sort () method. The function determines the order in which its two parameters are ordered in the sorted array. Assuming that the first argument should be before, the comparison function should return a value less than 0. Vice versa. If two values are equal, the order does not matter. For example, order the array in numeric size instead of a character descriptor, with the following code:

1 varA = [ -,4,1111,222];2 3A.sort ();//Alphabet Order: 1111,222, 44 5 A.sort (function (b) {6                  returnA-B;//returns a negative number, 0, positive number7 });8 9 A.sort (function (b) {Ten                  returnB-a;//the reverse order of the numerical size One});
(4) Concat ()

The Array.concat () method creates and returns a new array whose elements include the elements of the original array called concat () and each parameter of concat (). If any of these parameters itself is an array, then the elements of the array are connected, not the array itself.

1 var a = [12 ,3]; 2 3 a.concat (45);          // back to [1, 2, 3, 4, 5]
(5) Slice ()

The Array.slice () method returns a fragment or sub-array of the specified array. Its two parameters specify the starting and ending positions, respectively. The returned array contains all the array elements in the position specified by the first parameter and all but not the position specified by the second argument. If you specify only one parameter, the returned array will contain all elements from the start position to the end of the array. If a negative number appears in the argument, it represents the position relative to the last element in the array. For example, parameter 1 is specified to the last element, and 3 is specified to the third-lowest element. "Note" Slice () does not modify the called array. Here are some examples:

1 varA = [1,2,3,4,5];2 3A.slice (0,3);//back [1, 2, 3]4 5A.slice (3);//back [4, 5]6 7A.slice (1, -1)//back [2, 3, 4]8 9A.slice (-3, -2)//back [3]
(5) Splice ()

The Array.splice () method is a common method for inserting or deleting elements in an array. Unlike the slice () method and the Concat () method, splice () modifies the called Array.

Splice () is able to remove elements from an array, insert elements into an array, or do both of these operations. The array element after the insertion deletes the point, increasing or decreasing its index value as needed, so that the rest of the array remains contiguous. The first parameter of splice () specifies the starting position of the insertion and/or deletion. The second parameter specifies the number of elements that should be removed from the array. If you omit the second argument, all elements from the starting point to the end of the array are deleted. Splice () returns an array of deleted elements , or an empty array if no elements are deleted. For example:

1 varA = [1,2,3,4,5,6,7,8];2 3A.splice (4);//return [5, 6, 7, 8]; A is [1, 2, 3, 4]4 5A.splice (1,2);//return [2, 3]; A yes [1, 4]6 7A.splice (1,1);//return [4]; A is [1]
(6) push () and pop ()

The push () and Pop () methods allow arrays to be used as stacks. The push () method adds one or more elements to the end of the array and returns the new length of the array. The Pop () method is the opposite: it deletes the last element of the array, reduces the length of the array, and returns the value it deletes. Note: All two methods Modify and replace the original array instead of generating a new array of the modified version. Combination of push () and pop () enables advanced, post- out stacks using javascript arrays

1 var stack = []; 2 3 Stack.push (12);  // stack:[1, 2] return 245 stack.pop ();         // Stack:[1] Return 267 stack.push (3);    // stack:[1, 3]  returns 2
(7) Unshift () and Shift ()

The

Unshift () and Shift () methods behave much like the push () and Pop () methods, unlike the insertion and deletion of elements in the head of an array rather than the tail. Unshift () adds one or more elements to the head of the array and moves the existing elements to a higher index to get enough space and finally returns the new length of the array. Shift () deletes the first element of the array and returns it, and then moves all subsequent elements down one position to fill the empty array header. For example:

1 var a = []; 2 3 a.unshift (1);               // A:[1]  return: 145 a.unshift (n);           // a:[22,1]  return:67 a.shift (1);               // A:[1]  return:

The following is an array method in ECMAScript

(8) foreach ()

The foreach () method iterates through the array, invoking the specified element for each element. As described above, the passed function acts as the second parameter of the foreach (). foreach () then invokes the function with three parameters: the array element, the index of the element, and the group itself. If you only care about the values of the array elements, you can write a function with only one argument-the extra parameters will be ignored.

1 vardata = [1,2,3,4,5];2 3 varsum =0;4 5Data.foreach(function (value) {6sum + = value;//= = Add each value to sum7 });8 9Sum//=>15Ten  OneData.foreach(function (v, I, a) { AA[i] = v +1; - }) -  theData//=>[2, 3, 4, 5, 6]

(9) Map ()

The map () method passes each element of the called array to the specified function and returns a specified array that contains the return value of the function.

1 A = [123]; 2 3 b = A.map (function (x) {4        return x*x;                 // b Yes [1, 4, 9] 5 })

The function passed to map () is called the same way as the function passed to the foreach (). But the function passed to map () should have a return value. "Note" map () returns a new array: it does not modify the called array. If it is a sparse array, the returned sparse array is the same way: it has the same length, the same missing element.

(Fifth day) 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.