JavaScript array method (recommended), javascript Array

Source: Internet
Author: User
Tags javascript array

JavaScript array method (recommended), javascript Array

Arrays are frequently used in the test. arrays in javascript are somewhat different from arrays in other languages. In order to facilitate the study of arrays, the following section describes how to operate arrays, let's take a look.

Array Creation

There are two ways to create an Array in JavaScript: the first is to use an Array constructor:

Var arr1 = new Array (); // create an empty Array var arr2 = new Array (20 ); // create an Array containing 20 items var arr3 = new Array ("lily", "lucy", "Tom"); // create an Array containing 3 strings

The second basic way to create an array is to use the array literal representation:

Var arr4 = []; // create an empty array var arr5 = [20]; // create an array named var arr6 = ["lily", "lucy ", "Tom"]; // create an array containing three strings

When reading and setting the array value, square brackets should be used and a 0-based numeric index should be provided for the corresponding value:

Var arr6 = ["lily", "lucy", "Tom"]; // create an array alert (arr6 [0]) containing three strings; // lilyarr6 [1] = "mary"; // modify the second item to maryarr6 [3] = "sean"; // Add the fourth item to sean

The length attribute of the array in JavaScript can be modified. See the following example:

Var arr = ["lily", "lucy", "Tom"]; // create an array arr [arr. length] = "sean"; // Add an "sean" arr. length = arr. length-1; // Delete the last entry of the array

To determine whether an object is an Array object, we can use instanceof Array before ECMAScript 5. However, the instanceof operator assumes that there is only one global execution environment. If the webpage contains multiple frameworks, there are actually two or more different global execution environments, so there are two or more different versions of the Array constructor. If you input an array from a framework to another framework, the input array and the array originally created in the second framework have different constructors respectively.

ECMAScript 5 adds the Array. isArray () method. The purpose of this method is to determine whether a value is an array, regardless of the global execution environment in which it is created.

Array Method

The following describes the array method. The array method includes the array prototype method and the method inherited from the object. Here we only introduce the array prototype method, the array prototype methods mainly include the following:

Join ()
Push () and pop ()
Shift () and unshift ()
Sort ()
Reverse ()
Concat ()
Slice ()
Splice ()
IndexOf () and lastIndexOf () (Added in ES5)
ForEach () (ES5 new)
Map () (ES5 new)
Filter () (Added in ES5)
Every () (ES5 new)
Some () (ES5 new)
Reduce () and reduceRight () (new in ES5)

Method browser Support added to ES5:

Opera 11 +
Firefox 3.6 +
Safari 5 +
Chrome 8 +
Internet Explorer 9 +

The supported browser versions can be implemented through Array prototype extension. The following describes the basic functions of each method in detail.

1. join ()

Join (separator): A string is set up for the elements of the array. If this parameter is omitted, a comma is used as the separator by default. This method only receives one parameter, that is, the separator.

Var arr = [1, 2, 3]; console. log (arr. join (); // 1, 2, 3 console. log (arr. join ("-"); // 1-2-3console.log (arr); // [1, 2, 3] (original array unchanged)

The join () method can be used to implement repeated strings. You only need to input strings and the number of duplicates to return the repeated strings. The function is as follows:

function repeatString(str, n) {return new Array(n + 1).join(str);}console.log(repeatString("abc", 3)); // abcabcabcconsole.log(repeatString("Hi", 5)); // HiHiHiHiHi

2. push () and pop ()

Push (): can receive any number of parameters, add them one by one to the end of the array, and return the length of the modified array.
Pop (): removes the last entry from the end of the array, reduces the length value of the array, and returns the removed entry.

var arr = ["Lily","lucy","Tom"];var count = arr.push("Jack","Sean");console.log(count); // 5console.log(arr); // ["Lily", "lucy", "Tom", "Jack", "Sean"]var item = arr.pop();console.log(item); // Seanconsole.log(arr); // ["Lily", "lucy", "Tom", "Jack"]

3. shift () and unshift ()

Shift (): Delete the first entry of the original array and return the value of the deleted element. If the array is empty, undefined is returned.
Unshift: add the parameter to the beginning of the original array and return the length of the array.

This set of methods exactly corresponds to the push () and pop () methods above. One is the beginning of the operation array, and the other is the end of the operation array.

var arr = ["Lily","lucy","Tom"];var count = arr.unshift("Jack","Sean");console.log(count); // 5console.log(arr); //["Jack", "Sean", "Lily", "lucy", "Tom"]var item = arr.shift();console.log(item); // Jackconsole.log(arr); // ["Sean", "Lily", "lucy", "Tom"]

4. sort ()

Sort (): sort array items in ascending order-that is, the smallest value is located at the beginning, and the largest value is placed at the end.

During sorting, the sort () method calls the toString () transformation method of each array item, and then compares the obtained strings to determine how to sort them. Even if each item in the array is a numerical value, the sort () method is also a string, so the following situation occurs:

Var arr1 = ["a", "d", "c", "B"]; console. log (arr1.sort (); // ["a", "B", "c", "d"] arr2 = [13, 24, 51, 3]; console. log (arr2.sort (); // [13, 24, 3, 51] console. log (arr2); // [13, 24, 3, 51] (the meta array is changed)

To solve the preceding problem, the sort () method can receive a comparison function as a parameter so that we can specify which value is located before which value. The comparison function receives two parameters. If the first parameter is located before the second parameter, a negative number is returned. If the two parameters are equal, 0 is returned, if the first parameter is located after the second parameter, a positive number is returned. The following is a simple comparison function:

function compare(value1, value2) {if (value1 < value2) {return -1;} else if (value1 > value2) {return 1;} else {return 0;}}arr2 = [13, 24, 51, 3];console.log(arr2.sort(compare)); // [3, 13, 24, 51]

If you need to use the comparison function to generate the results in descending order, you only need to exchange the values returned by the comparison function:

function compare(value1, value2) {if (value1 < value2) {return 1;} else if (value1 > value2) {return -1;} else {return 0;}}arr2 = [13, 24, 51, 3];console.log(arr2.sort(compare)); // [51, 24, 13, 3]

5. reverse ()

Reverse (): reverse the order of array items.

Var arr = [13, 24, 51, 3]; console. log (arr. reverse (); // [3, 51, 24, 13] console. log (arr); // [3, 51, 24, 13] (original array changed)

6. concat ()

Concat (): Add parameters to the original array. This method will first create a copy of the current array, then add the received parameters to the end of the copy, and finally return the newly constructed array. Without passing parameters to the concat () method, It just copies the current array and returns a copy.

Var arr = [1, 3, 5, 7]; var arrCopy = arr. concat (9, [11,13]); console. log (arrCopy); // [1, 3, 5, 7, 9, 11, 13] console. log (arr); // [1, 3, 5, 7] (the original array has not been modified)

From the above test results, we can find that if the input is not an array, the parameter is directly added to the end of the array. If the input is an array, each item in the array is added to the array. But what if we input a two-dimensional array?

var arrCopy2 = arr.concat([9,[11,13]]);console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]console.log(arrCopy2[5]); //[11, 13]

In the above Code, the fifth item of the arrCopy2 array is an array containing two items, that is, the concat method can only add each item in the input array to the array, if some items in the input array are arrays, this array item will also be added to arrcopy2.

7. slice ()

Slice (): returns a new array consisting of items from the original array that specify the start subscript to the end subscript. The slice () method can take one or two parameters, that is, the start and end positions of the items to be returned. If there is only one parameter, the slice () method returns all items starting from the specified position of this parameter to the end of the current array. If there are two parameters, this method returns the item between the start and end positions-but does not include the item at the end position.

Var arr = [1, 3, 5, 7, 9, 11]; var arrCopy = arr. slice (1); var arrCopy2 = arr. slice (1, 4); var arrCopy3 = arr. slice (1,-2); var arrCopy4 = arr. slice (-4,-1); console. log (arr); // [1, 3, 5, 7, 9, 11] (original array not changed) console. log (arrCopy); // [3, 5, 7, 9, 11] console. log (arrCopy2); // [3, 5, 7] console. log (arrCopy3); // [3, 5, 7] console. log (arrCopy4); // [5, 7, 9]

ArrCopy only sets one parameter, that is, the initial subscript is 1. Therefore, the returned array starts from subscript 1 (including subscript 1) to the end of the array.
ArrCopy2 sets two parameters to return the subarray from the starting subscript (including 1) to the ending subscript (excluding 4.
ArrCopy3 sets two parameters and terminates the subscript as a negative number. When a negative number is displayed, the negative number is added with the value of array length (6) to replace the number at this position, therefore, it is a sub-array from 1 to 4 (not included.
In arrCopy4, both parameters are negative. Therefore, the array length 6 is added and converted to a positive number, which is equivalent to slice (2, 5 ).

8. splice ()

Splice (): a powerful array method. It can be used to delete, insert, and replace data.

Delete: You can delete any number of items. You only need to specify two parameters: the location of the first item to be deleted and the number of items to be deleted. For example, splice () deletes the first two items in the array.

Insert: you can insert any number of items to a specified position. You only need to provide three parameters: Start position, 0 (number of items to be deleted), and the item to be inserted. For example, splice (,) inserts 4 and 6 from position 2 of the current array.
Replace: you can insert any number of items to a specified position and delete any number of items at the same time. You only need to specify three parameters: start position, number of items to be deleted, and any number of items to be inserted. The number of inserted items does not have to be equal to the number of deleted items. For example, splice (,) deletes the entry at position 2 of the current array, and then inserts 4 and 6 from position 2.

The splice () method always returns an array that contains items deleted from the original array. If no items are deleted, an empty array is returned.

var arr = [1,3,5,7,9,11];var arrRemoved = arr.splice(0,2);console.log(arr); //[5, 7, 9, 11]console.log(arrRemoved); //[1, 3]var arrRemoved2 = arr.splice(2,0,4,6);console.log(arr); // [5, 7, 4, 6, 9, 11]console.log(arrRemoved2); // []var arrRemoved3 = arr.splice(1,1,2,4);console.log(arr); // [5, 2, 4, 4, 6, 9, 11]console.log(arrRemoved3); //[7]

9. indexOf () and lastIndexOf ()

IndexOf (): receives two parameters: the item to be searched and (optional) the index of the starting position. Search backward from the beginning of the array (position 0.
LastIndexOf: receives two parameters: the item to be searched and (optional) the index of the starting position. Search forward from the end of the array.

Both methods return the position of the item to be searched in the array, or return limit 1 if not found. When comparing the first parameter with each item in the array, the full operator is used.

var arr = [1,3,5,7,7,5,3,1];console.log(arr.indexOf(5)); //2console.log(arr.lastIndexOf(5)); //5console.log(arr.indexOf(5,2)); //2console.log(arr.lastIndexOf(5,4)); //2console.log(arr.indexOf("5")); //-1

10. forEach ()

ForEach (): traverses the array and runs the given function for each item in the array. This method does not return values. Parameters are of the function type. By default, parameters are transmitted. The parameters are the content of the traversal array, the corresponding array index, and the array itself.

Var arr = [1, 2, 3, 4, 5]; arr. forEach (function (x, index, a) {console. log (x + '|' + index + '|' + (a = arr);}); // The output is: // 1 | 0 | true // 2 | 1 | true // 3 | 2 | true // 4 | 3 | true/5 | 4 | true

11. map ()

Map (): A ing that is used to run a given function for each item in the array and returns an array composed of the results of each function call.

The following code uses the map method to calculate the square of each number in the array.

var arr = [1, 2, 3, 4, 5];var arr2 = arr.map(function(item){return item*item;});console.log(arr2); //[1, 4, 9, 16, 25]

12. filter ()

Filter (): "filter" function. Each item in the array runs a given function and returns an array that meets the filtering conditions.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];var arr2 = arr.filter(function(x, index) {return index % 3 === 0 || x >= 8;}); console.log(arr2); //[1, 4, 7, 8, 9, 10]

13. every ()

Every (): determines whether each item in the array meets the conditions. true is returned only when all items meet the conditions.

var arr = [1, 2, 3, 4, 5];var arr2 = arr.every(function(x) {return x < 10;}); console.log(arr2); //truevar arr3 = arr.every(function(x) {return x < 3;}); console.log(arr3); // false

14. some ()

Some (): determines whether a condition is met in the array. If one condition is met, true is returned.

var arr = [1, 2, 3, 4, 5];var arr2 = arr.some(function(x) {return x < 3;}); console.log(arr2); //truevar arr3 = arr.some(function(x) {return x < 1;}); console.log(arr3); // false

15. reduce () and reduceRight ()

Both methods implement all the items in the iterative array, and then construct a final returned value. The reduce () method starts from the first entry of the array and traverses the result one by one to the end. ReduceRight () starts from the last entry of the array and traverses forward to the first entry.

Both methods receive two parameters: a function called on each item and (optional) the initial value of the basic value of the merge.

The functions passed to reduce () and reduceRight () receive four parameters: the index of the previous value, current value, and item, and the array object. Any value returned by this function will be automatically passed to the next item as the first parameter. The first iteration occurs in the second item of the array. Therefore, the first parameter is the first item of the array, and the second parameter is the second item of the array.

The following code uses reduce () to sum the array. An initial value of 10 is added to the array at the beginning.

var values = [1,2,3,4,5];var sum = values.reduceRight(function(prev, cur, index, array){return prev + cur;},10);console.log(sum); //25

The above is a summary of the JavaScript array method (recommended) introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.