JavaScript array method Encyclopedia (recommended) _javascript tips

Source: Internet
Author: User
Tags array length numeric numeric value prev javascript array

Array in the written test will often appear in the face test, JavaScript in the array and other languages of the array is somewhat different, in order to facilitate the study of the array method, the following small series for everyone to organize the operation of the array of methods, together to see.

Array creation

There are two ways to create arrays in JavaScript, the first of which is to use the 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 an array literal notation:

var arr4 = []; Create an empty array
var ARR5 = [20];//Create an array containing 1 items
var arr6 = ["Lily", "Lucy", "Tom"];//Create an array containing 3 strings

When reading and setting the value of an array, you use square brackets and provide a 0-based numeric index of the corresponding value:

var arr6 = ["Lily", "Lucy", "Tom"]; Create an array containing 3 strings
alert (arr6[0]);//lily
arr6[1] = "Mary";//Modify the second item for Mary
arr6[3] = "Sean";//Add fourth to Sean

The length property of an array in JavaScript can be modified by looking at the following example:

var arr = ["Lily", "Lucy", "Tom"]; Create an array containing 3 strings
arr[arr.length] = "Sean";//Add a "Sean"
arr.length = arr.length-1 at subscript 3 (i.e. array tail) Deletes the last item of an array

If you need to determine whether an object is an array object, before ECMAScript 5, we can judge by the instanceof array, but the problem with the instanceof operator is that it assumes that there is only one global execution environment. If a Web page contains more than one frame, there is actually more than two different global execution environments, so there are more than two different versions of the Array constructor. If you pass an array to another frame from one frame, the passed-in array has its own different constructors than the array created in the second frame.

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

Array method

The following is an introduction to the methods of arrays, which have array prototypes and methods inherited from object objects, where we only introduce the prototype methods of arrays, and the array prototyping methods are mainly as follows:

Join ()
Push () and pop ()
Shift () and unshift ()
Sort ()
Reverse ()
Concat ()
Slice ()
Splice ()
IndexOf () and LastIndexOf () (ES5 added)
ForEach () (ES5 added)
Map () (ES5 added)
Filter () (ES5 added)
Every () (ES5 added)
Some () (ES5 added)
Reduce () and Reduceright () (ES5 added)

New method Browser support for ES5:

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

For supported browser versions, the array prototype extension can be implemented. The basic functions of each method are described in detail below.

1. Join ()

Join (Separator): Sets the element of an array to a string, separator as a delimiter, and omitted with the comma as the default, which receives only one parameter: the separator character.

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

The join () method enables you to implement a repeating string, which can be returned by passing in a string and repeating the number of times, and the function is as follows:

function repeatstring (str, n) {return
new Array (n + 1). Join (str);
}
Console.log (repeatstring ("abc", 3)); ABCABCABC
Console.log (repeatstring ("Hi", 5));//Hihihihihi

2, push () and pop ()

Push (): You can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array.
Pop (): Removes the last item at the end of the array, reduces the length value of the array, and then returns the removed item.

var arr = ["Lily", "Lucy", "Tom"];
var count = Arr.push ("Jack", "Sean");
Console.log (count); 5
Console.log (arr);//["Lily", "Lucy", "Tom", "Jack", "Sean"]
var item = Arr.pop ();
Console.log (item); Sean
Console.log (arr);//["Lily", "Lucy", "Tom", "Jack"]

3. Shift () and unshift ()

Shift (): Deletes the first item of the original array, returns the value of the deleted element, and returns undefined if the array is empty.
Unshift: Adds a parameter to the beginning of the original array and returns the length of the array.

This set of methods corresponds exactly to the push () and Pop () method above, the beginning of an array of operations and the end of an array of operations.

var arr = ["Lily", "Lucy", "Tom"];
var count = Arr.unshift ("Jack", "Sean");
Console.log (count); 5
Console.log (arr);//["Jack", "Sean", "Lily", "Lucy", "Tom"]
var item = Arr.shift ();
Console.log (item); Jack
Console.log (arr);//["Sean", "Lily", "Lucy", "Tom"]

4, sort ()

Sort (): Arranges the array items in ascending order-that is, the smallest values are at the front and the largest values are at the bottom.

When sorting, the sort () method invokes the ToString () transformation method for each array item, and then compares the resulting string to determine how to sort. Even if each item in the array is a numeric value, the sort () method compares the string, so the following can occur:

var arr1 = ["A", "D", "C", "B"];
Console.log (Arr1.sort ()); ["A", "B", "C", "D"]
arr2 = [3;
Console.log (Arr2.sort ()); [3, Yi]
console.log (ARR2);//[13, 24, 3, 51] (meta array changed)

To solve the above problem, the sort () method can receive a comparison function as an argument so that we specify which value precedes which value. The comparison function receives two arguments, returns a negative number if the first argument should be in the second, and returns 0 if the two arguments are equal, and returns a positive number if the first argument should be positioned after the second. 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 = [3];
Console.log (Arr2.sort (Compare)); [3, 13, 24, 51]
   

If you need to produce a descending sort result from a comparison function, you can simply exchange the value returned by the comparison function:

function Compare (value1, value2) {
if (value1 < value2) {return
1;
} else if (value1 > value2) {
re turn-1;
} else {return
0;
}
}
ARR2 = [3];
Console.log (Arr2.sort (Compare)); [51, 24, 13, 3]

5, reverse ()

Reverse (): Reverses the order of the array items.

var arr = [3];
Console.log (Arr.reverse ()); [3, Wuyi,
Console.log] (arr);//[3, 51, 24, 13] (original array change)

6, Concat ()

Concat (): Adds a parameter to the original array. This method first creates a copy of the current array, then adds the received parameter to the end of the replica, and finally returns the newly constructed array. Without passing arguments to the concat () method, it simply 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, one]
console.log (arr);//[1, 3, 5, 7] (original array not modified)

From the above test results can be found: the incoming is not an array, then directly add parameters to the array, if the incoming is an array, the array of items are added to the array. But what if the incoming is 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 preceding code, the fifth item in the ARRCOPY2 array is an array that contains two items, meaning that the Concat method can only add each entry in the incoming array to the array, and if some of the incoming arrays are arrays, the array item is added to the arrCopy2 as an item.

7, Slice ()

Slice (): Returns a new array of items from the original array specifying the start subscript to the end subscript. The slice () method can accept one or two parameters, that is, to return the starting and ending positions of the items. In the case of only one parameter, the slice () method returns all items starting at the specified position of the parameter to the end of the current array. If there are two parameters, the method returns the item between the start and end positions-but not the ending 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 unchanged)
Console.log (arrcopy);//[3, 5, 7, 9, one]
console.log (arrCopy2);//[3, 5, 7]
Conso Le.log (ARRCOPY3); [3, 5, 7]
Console.log (ARRCOPY4);//[5, 7, 9]

Arrcopy sets only one argument, that is, the starting subscript is 1, so the returned array starts with subscript 1 (including subscript 1) to the end of the array.
ArrCopy2 sets two parameters, returning a substring of the starting subscript (including 1) to the beginning of the terminating subscript (excluding 4).
ArrCopy3 sets two parameters, terminates the subscript as a negative number, and, when negative numbers occur, replaces the numbers with the length of the array (6), so it is a child array starting at 1 to 4 (not included).
Both parameters in ArrCopy4 are negative, so the array length 6 is converted to a positive number, so it is equivalent to slice (2,5).

8, Splice ()

Splice (): A powerful array method that can be used in many ways to delete, insert, and replace.

Delete: You can delete any number of items by specifying only 2 parameters: the position of the first item to delete and the number of items to delete. For example, splice (0,2) deletes the first two items in the array.

Insert: You can insert any number of items to a specified location by providing only 3 parameters: Start position, 0 (number of items to delete), and items to insert. For example, splice (2,0,4,6) inserts 4 and 6 starting at position 2 of the current array.
Replace: You can insert any number of items to a specified location and delete any number of items at the same time, specifying only 3 parameters: Start position, 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. For example, splice (2,1,4,6) deletes the entry for the current array position 2, and then inserts 4 and 6 from position 2.

The splice () method always returns an array containing the items removed from the original array, or an empty array if no items are deleted.

var arr = [1,3,5,7,9,11];
var arrremoved = Arr.splice (0,2);
Console.log (arr); [5, 7, 9, one]
console.log (arrremoved);//[1, 3]
var arrRemoved2 = Arr.splice (2,0,4,6);
Console.log (arr); [5, 7, 4, 6, 9, one]
console.log (ARRREMOVED2);//[]
var arrRemoved3 = Arr.splice (1,1,2,4);
Console.log (arr); [5, 2, 4, 4, 6, 9, one]
console.log (ARRREMOVED3);//[7]

9, IndexOf () and LastIndexOf ()

IndexOf (): Receives two parameters: the Xiang (optional) To find indicates the index at which to find the start point. Where the backward lookup begins at the beginning of the array (position 0).
LastIndexOf: Receives two parameters: the Xiang (optional) To find indicates the index at which to find the start point. Where the forward lookup begins at the end of the array.

Both methods return the position of the item to find in the array, or return to 1 if it is not found. The strict equality operator is used when comparing the first argument with each item in the array.

var arr = [1,3,5,7,7,5,3,1];
Console.log (Arr.indexof (5)); 2
Console.log (Arr.lastindexof (5));//5
Console.log (Arr.indexof (5,2));//2
Console.log ( Arr.lastindexof (5,4)); 2
Console.log (Arr.indexof ("5"));//-1

10, ForEach ()

ForEach (): An array of traversal loops in which each item in an array runs the given function. This method has no return value. Parameters are function types, and the default arguments are: Traversal of the array contents, the corresponding array index, the array itself.

var arr = [1, 2, 3, 4, 5];
Arr.foreach (function (x, index, a) {
console.log (x + ' | ' + + index + ' | ' + (a = = = arr));
};
Output is:
//1|0|true
//2|1|true
//3|2|true
//4|3|true
//5|4|true

11, Map ()

Map (): Refers to "mapping", in which each item in an array runs the given function, returning an array of the results of each function call.

The following code uses the map method to implement 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 the given function, returning an array that satisfies the filter conditions.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, ten];
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 satisfies the condition, and returns true only if all items satisfy the condition.

var arr = [1, 2, 3, 4, 5];
var arr2 = arr.every (function (x) {return
x <;
}); 
Console.log (ARR2); True
var arr3 = arr.every (function (x) {return
x < 3;
}); 
Console.log (ARR3); False

14, some ()

Some (): Determines whether an array has an item that satisfies the condition, and returns True if one of the conditions is met.

var arr = [1, 2, 3, 4, 5];
var arr2 = arr.some (function (x) {return
x < 3;
}); 
Console.log (ARR2); True
var arr3 = arr.some (function (x) {return
x < 1;
}); 
Console.log (ARR3); False

15, reduce () and reduceright ()

Both of these methods implement all the items of an iterative group, and then build a value that is ultimately returned. The reduce () method begins with the first item of the array, traversing to the last. Reduceright () begins with the last item in the array and traverses forward to the first item.

Both methods receive two parameters: a function called on each item and (optionally) an initial value that is the base of the merge.

Functions passed to reduce () and Reduceright () receive 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the first argument is the first item of the array, and the second argument is the second item of the array.

The following code implements the array summation with reduce (), and the array starts with an initial value of 10.

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 small set to introduce the JavaScript array method encyclopedia (recommended), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.