The array prototype provides a lot of methods, mainly divided into three kinds, one is to change its value, one is not to change its value, and the other is the traversal method.
Based on ES6, there are a total of 9 methods to change its value, namely POP, Push, reverse, Shift, sort, splice, unshift, and two new ES6 methods copyWithin and Fill.
I. Stack method:
Array objects can act like stacks, which are data structures that restrict insertion and deletion of items. The stack is a LIFO (last-in-first-out) structure, In which the most recently added item is deleted First. Insertion (called push, push) and deletion (called pop, pop) of data items occur only in one place on the stack, at the top. The ECMAScript array provides push() and POP () methods to implement stack-like behavior.
1, pop
(1) The pop() method removes the last element of an array, reduces the array length, and returns the element. In the case of stacks, this process is the top of the stack pops.
(2) Because of the clever design, pop method can be applied to the array object, that is, duck discrimination. As follows:
(3) If an array object does not have a length attribute, the object will be created with a length attribute of 0. As follows:
var o = {0:"cat".1:"dog".2:"cow".3:"chicken".4:"mouse"};
var item = Array.prototype.pop.call(o);
Copy the code
2, push
The push() method adds one or more elements to the end of the array and returns the array’s new length. In the case of stacks, this process is called top push.
Arr. Push (element1,… , elementN)
(2) Like the POP method, the push method can also be applied to array-like objects. If length cannot be converted to a value or the length attribute does not exist, the index of the inserted element is 0, and the length attribute does not exist, it will be created.
var o = {0:"football".1:"basketball"};
var i = Array.prototype.push.call(o, "golfball");
Copy the code
(3) The push method actually uses the length attribute to decide where to start inserting a given value.
By using the feature that push inserts elements according to the length attribute, the array can be combined, and the second number is combined into the first array, that is, the first array becomes a new array, and the second array does not change.
Examples are as follows:
Two, sorting method:
Arrays have two methods that you can use to reorder elements: reverse() and sort(). As the name suggests, the reverse() method simply arranges array elements in reverse.
1, the sort
The sort() method sorts the elements of the array and returns the array.
Arr. Sort ([comparefn])
- Comparefn is optional if omitted.
- Array elements are sorted according to the order of their Unicode points converted to strings.
- By default, sort() rearranges array elements in ascending order, with the smallest value in front and the largest value behind. To this end,
Therefore, sort() calls the String() transformation function on each item and compares the strings to determine the order. Even if the array’s elements are all numeric, the array is converted to a string and then compared and sorted. Such as
The values in the array start out in the correct order, but calling sort() reorders them as strings. So even though 5 is less than 10, the string “10” precedes the string “5”, so 10 will still precede 5. Obviously, this is not the most appropriate in most cases. To do this, the sort() method can accept a comparison function that determines which value should come first.
The comparefn comparison function takes two arguments and returns a negative value if the first argument should come before the second; If two arguments are equal, 0 is returned; Returns a positive value if the first argument should come after the second. Here is an example of using a simple comparison function:
function compare (v1,v2){
if(v1<v2){
return -1;
} else if (v1>v2) {
return 1;
} else {
return 0; }}Copy the code
After passing the comparison function to the sort() method, the values in the array remain in the correct order after sorting
The comparison function can also be abbreviated as:
values.sort((a,b) = > a<b ? 1: a>b ? -1 : 0);
Copy the code
(2) If the array element is a number, or an object (such as a Date object) whose valueOf() method returns a number, the comparison function can be written as:
function compare (v1,v2){
return v2 - v1;
}
Copy the code
(3) As above, SORT also benefits from duck discrimination, for example:
Note: When you use sort’s duck-discriminating feature, if an array-like object does not have a length attribute, it does not sort or add a length attribute to it.
2, reverse
The reverse() method reverses the position of the elements in the array so that the first one becomes the last one, and the last one becomes the first one, and returns a reference to the array.
(1) Syntax: arr.reverse()
var array = [1.2.3.4.5];
var array2 = array.reverse();
console.log(array); / /,4,3,2,1 [5]
console.log(array2===array); // true
Copy the code
Again, reverse is also a beneficiary of duck discrimination, and the range of reverse elements is restricted by the length attribute. As follows:
If the length attribute is less than 1 or the length attribute is not numeric, the original array object remains unchanged. The object does not create the length attribute even if it does not exist. In particular, when the length attribute is large, the “index” of an array-like object will be as close to Length as possible.
Iii. Queue method:
Just as stacks restrict access to data structures In the form of LIFO, queues restrict access In the form of FIFO (first-in-first-out). Queues add data at the end of the list, but get data from the beginning of the list. Because of the push() method, which adds data to the end of the data, there is only one way to get data from the beginning of the array to simulate the queue. This array method is called shift(), and it removes the first item of the array and returns it, then the array length is reduced by one. With Shift () and push(), arrays can be used as queues:
1, the shift
The shift() method removes the first element of the array, decreases the length by 1, and returns the element. The end of a queue pops the last element.
(1) Syntax: arr.shift()
(2) Also benefiting from duck discrimination, Shift can still handle array-like objects. As follows:
(3) If the length property of the array object does not exist, add the length property and initialize it to 0. As follows:
2, push
Inserts a new element at the end of the queue, consistent with push().
Four, operation method:
1, the splice
The splice() method modifies the array by replacing old elements with new ones. Splice is a common method used in complex array manipulation scenarios, especially when you need to maintain a reference to an array and delete or add elements in place.
Arr. splice(start, deleteCount [, item1[, Item2 [,…]]])
Start: specifies which digit to start the modification. If the array length is exceeded, the contents are appended from the end of the array; If it is negative, the index position specified is the same as length+start (length is the length of the array), representing the -start bit from the end of the array.
DeleteCount: specifies the number of elements to be deleted. If the value is 0, the elements are not deleted. In this case, at least one new element should be added, and if it is greater than the sum of elements after start, both start and subsequent elements will be deleted.
ItemN: Specifies the new element. By default, only the array element is deleted.
Return value: An array of deleted elements from the original array, or an empty array if not deleted.
❑ deleted. Splice () needs to be passed two parameters: the location of the first element to delete and the number of elements to delete. You can remove any number of elements from an array, such as splice(0, 2), which removes the first two elements.
❑ inserted. Splice () needs to be passed three arguments: the start position, 0 (number of elements to delete), and the element to insert, which can be inserted at the specified position in the array. The third argument can be followed by a fourth argument, a fifth argument, or any number of elements to be inserted. For example, splice(2, 0,”red”, “green”) inserts the strings “red” and “green” from array position 2.
❑ replacement. Splice () inserts new elements at specified positions while deleting elements, again passing in three arguments: the starting position, the number of elements to delete, and any number of elements to insert. The number of elements to be inserted is not necessarily the same as the number of elements to be deleted. For example, splice(2, 1, “red”,”green”) removes an element at position 2 and inserts “red” and “green” into the array starting at that position.
The splice() method always returns an array containing the elements that were deleted from the array (or an empty array if no element was deleted).
Here’s an example:
/ / delete
var array = ["apple"."boy"];
var splices = array.splice(1.1);
console.log(array); // ["apple"]
console.log(splices); // ["boy"], delete an element from the array with subscript 1, and delete an element
/ / new
array = ["apple"."boy"];
splices = array.splice(2.1."cat");
console.log(array); // ["apple", "boy", "cat"]
console.log(splices); // [], you can see that since start exceeds the length of the array, the element is added from the end of the array, and the original array will not be deleted
/ / replace
array = ["apple"."boy"];
splices = array.splice(-2.1."cat");
console.log(array); // ["cat", "boy"]
console.log(splices); // ["apple"], we can see that when start is negative, we start from the -start bit at the end of the array, remove an element, and insert an element from there
array = ["apple"."boy"];
splices = array.splice(-3.1."cat");
console.log(array); // ["cat", "boy"]
console.log(splices); // ["apple"], so that even if -start exceeds the array length, the array is deleted from the first digit by default
array = ["apple"."boy"];
splices = array.splice(0.3."cat");
console.log(array); // ["cat"]
console.log(splices); // ["apple", "boy"], we can see that when deleteCount is greater than the sum of elements after start,start and all elements after start are deleted
Copy the code
(2) Again, Splice benefits from duck discrimination,
O removes an attribute and returns the deleted attribute with Length-1.
(3) If you need to delete an existing element from the array, see the following:
var array = ['a'.'b'.'c'];
array.splice(array.indexOf('b'), 1);
Copy the code
2, unshift
Unshift () method: As the name suggests, unshift() does the opposite of shift() : it adds any number of values to the beginning of the array and returns the new array length. By using unshift() and pop(), you can simulate the queue in the opposite direction, adding new data at the beginning of the array and fetching data at the end.
Arr. Unshift (element1,… , elementN)
A length of 5 indicates that the two attributes were successfully inserted into the array. It’s the head of the queue.
(2) If an array is passed, then:
(3) Unshift also benefits from duck discrimination, as shown below:
Note: If a class array object does not specify a length attribute, {0: ‘gray’, 1: ‘green’, 2: ‘blue’, length: 1},unshift will assume that the length of the array is 0, and the insertion will start at the position of the object subscript 0, and the corresponding position attribute will be replaced. At this point, the length attribute of the array-like object is initialized to be the number of inserted elements.
var o2 = {0:"red".1:"green".2:"blue"};
var length = Array.prototype.unshift.call(o2,"gray"."orange"."black");
Copy the code
varo2 = {0:"red".1:"green".2:"blue"};
var length = Array.prototype.unshift.call(o2,"gray"."orange"."black");
Copy the code
If too many attributes are inserted, it seems that the original data will disappear ????
Five, copy and fill methods:
ES6 has two new methods: batch copy method copyWithin() and fill array method fill()
1, copyWithin
The copyWithin() method is based on the ECMAScript 2015 (ES6) specification and is used for substitutions between elements within an array, meaning that both the replaced element and the replaced element are elements within the array.
Arr. CopyWithin (target, start[, end = this.length])
Target: index of the position at which the insertion starts (subscript is 0) [Mandatory];
Start: index of the element to be copied;
End: The index to end the copied element.
The return value is the copied array.
// The copied element index from start to end includes the position of start index, but does not include the position of end index
var arr=[1.2.3.4.5.6];
arr.copyWithin(1.2.3); // copy the elements in index 2~3 and insert them into index 1.
Copy the code
The results are as follows:
// If there is only one argument, i.e. the index of the insertion position, then the default is to copy from index 0 to the next one
var array=[1.2.3.4.5];
array.copyWithin(2); // Copy all elements starting at index 0 and insert them sequentially starting at index 2.
Copy the code
The results are as follows:
// If there are two arguments, the first argument is the index of the insertion position, and the second argument is the index of the start position
var array=[1.2.3.4.5];
array.copyWithin(1.3); // Copy the elements starting at index 3 and after, and insert them at index 1 and after
Copy the code
The results are as follows:
// If the argument is negative, count backwards from the last element, or add the length of the original array, and count as positive
array=[1.2.3.4.5];
array.copyWithin(-1, -3);// Copy starts at (-3+5) 2 and the following elements are inserted at (-1+5) 4.
Copy the code
The results are as follows:
(2) As above, copyWithin benefits from duck discrimination, for example:
Note: If the array-like object does not specify a length attribute,copyWithin assumes that the array is undefined.
2, the fill
Fill () is also used for array element substitution, but slightly different from copyWithin, it is mainly used to replace elements within a specified range of the array with a value.
Arr. Fill (value, start[, end = this.length])
Value: is the value of the element to be replaced by. Start is the index of the start position and end is the index of the end position
[note] index start is not included in index end
(2) Usage is basically the same as copyWithin(). Examples are as follows:
(3) As above, Fill also benefits from duck discrimination, for example:
Note: If the array-like object does not specify a length attribute,copyWithin assumes that the array is undefined.