Summary of array methods in Javascript

Source: Internet
Author: User

Summary of array methods in Javascript

Array. prototype defines many methods to operate arrays. The following describes some methods in ECMAScript3.

1. Array. join () method

This method converts all elements in the array into strings and connects them together according to the specified symbols. The final generated string can contain a parameter, which is the symbol used to connect the array elements. The default value is comma.

?

1

2

3

4

5

6

7

8

Var ay = [1, 2, 3];

Ay. join (); // => "1, 2, 3"

Ay. join ("+"); // => "1 + 2 + 3"

Ay. join (""); // => "1 2 3"

Ay. join (""); // = & gt; "123"

 

Var by = new Array (10) // create an empty Array with a length of 10

By. join ("-"); // => "---------" connect 10 null Elements

2. Array. reverse () method

This method reverses the elements in the array and returns the reverse array. This method changes the current array and does not create a new array.

 

The Code is as follows:


Var a = [1, 2, 3];
A. reverse (). join (); // => "3, 2, 1", then a = [3, 2, 1]

 

3. Array. sort () method

This method sorts the elements in the array and returns the sorted array. When the sort () method does not contain parameters, the array is sorted alphabetically. If the array contains undefined elements, it is routed to the end of the array.

 

The Code is as follows:


Var as = ["banana", "cherry", "apple"];
As. sort ();
As. join ("+"); // => "apple + banana + cherry"

 

You can also input a comparison function as a parameter for the sort () method to sort the array by the specified comparison function. If the return value of the comparison function is less than 0, the first parameter is in the front. If the return value is greater than 0, the second parameter is in the front. If the two parameters are equal, 0 is returned.

The Code is as follows:


Var sy = [1111,222,];
Sy. sort (); // => "1111,222, 33,4"
Sy. sort (function (a, B ){
Return a-B;
}); // => "4,33, 222,1111"


Note: It is best to use an anonymous function here, because only one call is required and the function name is not required.

 

4. Array. concat () method

This method creates and returns a new array, connects each element in the original array element and method to form a new array. This method does not call parameters in a method recursively.

 

The Code is as follows:


Var a = [1, 2, 3];
A. concat (); // => ", 5"
A. concat ([]); // => ", 5"
A. concat ([], []); // => ", 7"
A. concat (4, [5, [6, 7]); // => "1, 2, 4, 5, [6, 7]"

 

5. Array. slice () method

This method returns a fragment or sub-array of the specified array. This method can have two parameters to specify the start and end positions of the fragment, respectively, the returned array contains the elements specified by the first parameter and all the array elements to but not at the position specified by the second parameter. If there is only one parameter, it contains from the specified start position to the end of the array. The parameter can be a negative value, indicating the position relative to the last element in the array. This method does not modify the called array.

 

The Code is as follows:


Var d = [1, 2, 3, 4, 5];
D. slice (1, 2); // => "2"
D. slice (1,-1); // => "2, 3, 4"
D. slice (3); // => "4, 5"
D. slice (-3,-1); // => "3, 4"

 

6. Array. splice () method

This method is a common method for inserting or deleting elements in an array. This method modifies the original array. This method can contain multiple parameters. The first parameter specifies the starting position of the element to be inserted or deleted in the array. The second parameter specifies the number of elements to be deleted, if this parameter is not specified, the starting position and subsequent elements are deleted. The parameters after the two parameters specify the elements inserted into the array. This method returns an array composed of the deletion elements.

 

1

2

3

4

5

6

7

Var e = [1, 2, 3, 4, 5, 6];

E. splice (4); // => Returns [5, 6]; e is [1, 2, 4]

E. splice (); // => Returns [2, 3]; e is []

 

Var f = [1, 2, 3, 4, 5];

F. splice (, "a", "B"); // => return []; f is [1, 2, a, B, 3, 4, 5]

F. splice (, [], 3); // => return [a, B]; f is [, [], 5]

7. push () and pop () Methods

These two methods use arrays as stacks. The push () method adds one or more elements to the end of the array and returns the length of the array. The pop () method is to delete the last element of the array, reduce the array length and return the deleted Value.

8. unshift () and shift () Methods

The two methods are used to add or delete the array header. The unshift () method adds one or more elements to the array header and returns the array length. The shift () method deletes the first element of the array and returns the result.

 

1

2

3

4

5

6

Var a = []; // []

A. push (1, 2); // [1, 2]

A. pop (); // [1]

 

A. unshift (2, 3); // [2, 3, 1]

A. shift (); // [3, 1]

9. toString () and toLocaleString () Methods

The two methods are to convert each element of the array into a string, and toString () is to convert each element into a string and the output is separated by commas. The toLocaleString () method is used to convert each element of the array into a string by calling toLocaleString () and connect with a localized separator.

The following describes several special array methods in ECMAScript5. Before introducing the methods, let's get a general idea. The first parameter of most methods accepts a function and calls this function once for each element of the array. If it is a sparse array, nonexistent elements do not call the function. In most cases, the called function uses three parameters: array elements, element indexes, and the array itself.

1. forEach () method

This method traverses the array from start to end. Each element of the array calls the specified function. This method does not terminate until all array elements are traversed. To terminate the service in advance, you must put forEach () in the try block and throw an exception.

 

1

2

3

4

5

6

7

8

9

Var data = [1, 2, 3, 4, 5]

Var sum = 0;

Data. forEach (function (value) {// => value is an array element.

Sum + = value;

}) // => 15

 

Data. forEach (function (value, I, a) {// => three parameters refer to array elements, element indexes, and arrays respectively.

A [I] = v + 1;

}) // => Data = [2, 3, 4, 5, 6]

2. map () method

This method passes each element of the array to the specified function and returns a new array that contains the return value corresponding to the array element call function. If it is a sparse array, the returned new array is also a coefficient array of the same structure.

 

1

2

3

4

Var a = [1, 2, 3];

Var B = a. map (function (v ){

Return v * v;

}) // => B = [1, 4, 9]

3. filter () method -- similar to conditional Filtering

This method returns a subset of the original array. The passed function is used for logic determination. true or false is returned. If the returned value is true, it can be converted to true, the element of the current array is a member of the subset and is added to the returned array. This method skips the empty elements of the sparse array.

 

1

2

3

4

5

6

7

Var a = [5, 4, 3, 2, 1]

Var smalla = a. filter (function (v ){

Return v <3;

}) // => Return [2, 1]

Var everya = a. filter (function (v, I) {// => I indicates the element index

Return I % 2 = 0;

}) // => Return [5, 3, 1]


4. every () and some () Methods

These two methods are used to logically determine the array. Each element of the array is determined using the specified function and true or false is returned.
The every () method returns true only when all elements in the array call the determining function returns true. Otherwise, false is returned.
The some () method returns true if at least one element in the array is called to determine whether the function returns true. Otherwise, false is returned.

Both of these methods do not traverse array elements once the returned values are confirmed.

5. reduce () and reduceRight () Methods

These two methods use the specified function to combine array elements to generate a single value.
Reduce () requires two parameters. The first is to execute the operation function for simplifying the combination, and the second is the initial value of the combination. Unlike the previous methods, the common three parameters (array elements, element indexes, and arrays) are used as the 2 ~ Four parameters are passed to the function. The first parameter is the result of a combination calculation so far.
If it is for an empty array and does not specify the initial value, calling the reduce () method will cause a type error.
The reduceRight () and reduce () methods work in the same way. The difference is that they are processed by array indexes from high to low (that is, merged from right to left)

6. indexOf () and lastIndexOf () Methods

Both methods are used to search for a specific value in the entire array and return the index value of the First Matching Element. If not,-1 is returned. the indexOf () method searches from start to end, while the lastIndexOf () method searches from end to end.

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.