js array common methods

Posted by Peter on Sun, 26 Dec 2021 08:47:33 +0100

1.join() (array to string)

Array to string, the method only receives one parameter: the default comma separator ().

   
  1. <script>
  2. var arr=[ 1, 2, 3, 4];
  3. console.log(arr.join()); //1,2,3,4
  4. console.log(arr.join( ":")); //1:2:3:4
  5. console.log(arr); //[1,2,3,4], the original array remains unchanged
  6. </script>

join() implements duplicate strings

   
  1. <script>
  2. function repeatStr(str, n) {
  3. return new Array(n + 1).join(str);
  4. }
  5. console.log(repeatStr( "hi", 3)); //Hi, hi, hi
  6. console.log(repeatStr( "Hi", 3)); //HiHiHi
  7. console.log(repeatStr( 1, 3)); //111
  8. </script>

2.push() and pop() (array tail operation)

push(): method adds one or more elements to the end of the array and returns a new length.

pop(): method used to delete and return the last element of the array.

   
  1. <script>
  2. var arr=[ 1, 2, 3, 4];
  3. //push
  4. var push_arr=arr.push( "Tom", "Sun");
  5. console.log(arr); //[1,2,3,4,"Tom","Sun"];
  6. console.log(push_arr); // 6
  7. //pop
  8. var pop_arr=arr.pop();
  9. console.log(arr); //[1,2,3,4,"Tom"];
  10. console.log(pop_arr); // Sun
  11. </script>

3.shift() and unshift() (array header operation)

shift(): the method is used to delete the first element of the array and return the value of the first element.

unshift(): the method adds one or more elements to the beginning of the array and returns a new length.

   
  1. <script>
  2. var arr=[ 1, 2, 3, 4];
  3. //shift
  4. var shift_arr=arr.shift();
  5. console.log(arr); // [2, 3, 4]
  6. console.log(shift_arr); // 1
  7. //unshift
  8. var unshift_arr=arr.unshift( "Tom");
  9. console.log(arr); // ["Tom", 2, 3, 4]
  10. console.log(unshift_arr); // 4
  11. </script>

4.sort() (sort)

Method is used to sort the elements of an array.

   
  1. <script>
  2. var arr=[ 1, 100, 5, 20];
  3. console.log(arr.sort()); // [1, 100, 20, 5]
  4. console.log(arr); // [1, 100, 20, 5] (original array changed)
  5. </script>

Please note that the above code does not sort the numbers according to the size of the number, but according to the order of character coding. To achieve this, you must use a sorting function:

Ascending order:

   
  1. <script>
  2. var arr=[ 1, 100, 5, 20];
  3. function sortNumber(a,b){ return a - b};
  4. console.log(arr.sort(sortNumber)); //[1, 5, 20, 100]
  5. console.log(arr); //[1, 5, 20, 100] (original array changed)
  6. </script>

Descending order:

   
  1. <script>
  2. var arr=[ 1, 100, 5, 20];
  3. function sortNumber(a,b){ return b - a};
  4. console.log(arr.sort(sortNumber)); // [100, 20, 5, 1]
  5. console.log(arr); // [100, 20, 5, 1] (original array changed)
  6. </script>

5.reverse() (reverse array)

Method is used to reverse the order of elements in an array.

   
  1. <script>
  2. var arr=[ 12, 25, 5, 20];
  3. console.log(arr.reverse()); // [20, 5, 25, 12]
  4. console.log(arr); // [20, 5, 25, 12] (original array changed)
  5. </script>

6.concat() (connect two or more arrays)

The concat() method is used to join two or more arrays. This method does not change the existing array, but only returns a copy of the connected array. Without passing arguments to the concat() method, it simply copies the current array and returns a copy.

   
  1. <script>
  2. var arr=[ 1, 2, 3, 4];
  3. var arr2=[ 11, 12, 13]
  4. var arrCopy = arr.concat(arr2);
  5. console.log(arr.concat()); // [1, 2, 3, 4] (copy array)
  6. console.log(arrCopy); // [1, 2, 3, 4, 11, 12, 13]
  7. console.log(arr); // [1, 2, 3, 4] (original array unchanged)
  8. </script>

What if the parameter passed in is a two-dimensional array?

   
  1. <script>
  2. var arr=[ 1, 2, 3, 4];
  3. var arr2=[ 11,[ 12, 13]]
  4. var arrCopy = arr.concat(arr2);
  5. console.log(arrCopy); // [1, 2, 3, 4, 11, Array(2)]
  6. console.log(arr); // [1, 2, 3, 4] (original array unchanged)
  7. </script>

As can be seen from the above code, the concat method can only add each item in the incoming array to the array. If some items in the incoming array are arrays, this array item will also be added to arrCopy as an item.

7.slice() (array interception)

arr.slice(start , end);

Start: required. Specify where to start. If it is negative, it specifies the position from the end of the array. That is, - 1 refers to the last element, - 2 refers to the penultimate element, and so on.

End: optional. Specify where to end the selection. This parameter is the array subscript at the end of the array fragment. If this parameter is not specified, the segmented array contains all elements from start to the end of the array. If this parameter is negative, it specifies the elements starting from the end of the array.

Return value: returns a new array containing the elements in the arr from start to end (excluding this element).

   
  1. <script>
  2. var arr = [ 1, 4, 6, 8, 12];
  3. var arrCopy1 = arr.slice( 1);
  4. var arrCopy2 = arr.slice( 0, 4);
  5. var arrCopy3 = arr.slice( 1, -2);
  6. var arrCopy4 = arr.slice( -5, 4);
  7. var arrCopy5 = arr.slice( -4, -1)
  8. console.log(arrCopy1); // [4, 6, 8, 12]
  9. console.log(arrCopy2); // [1, 4, 6, 8]
  10. console.log(arrCopy3); // [4, 6]
  11. console.log(arrCopy4); // [1, 4, 6, 8]
  12. console.log(arrCopy5); // [4, 6, 8]
  13. console.log(arr); // [1, 4, 6, 8, 12] (original array unchanged)
  14. </script>

8.splice() (array update)

The splice() method adds / removes items to / from the array, and then returns the deleted items. (this method changes the original array)

arr.splice(index , howmany , item1,.....,itemX)

index: required. Integer that specifies the position of the item to be added / deleted. Use a negative number to specify the position from the end of the array.

howmany: required. Number of items to delete. If set to 0, the item is not deleted.

item1, ..., itemX: optional. Adds a new item to the array.

Return value: an array containing deleted elements. If no elements are deleted, an empty array is returned.

   
  1. <script>
  2. var arr = [ "Zhang San", "Li Si", "Wang Wu", "Xiao Ming", "Xiao Hong"];
  3. /**************Delete "Wang Wu"****************/
  4. var arrReplace1 = arr.splice( 2, 1);
  5. console.log(arrReplace1); // ["king five"]
  6. console.log(arr); // ["Zhang San", "Li Si", "Xiao Ming", "Xiao Hong"] (original array changed)
  7. //Delete multiple
  8. var arrReplace2 = arr.splice( 1, 2);
  9. console.log(arrReplace2); // ["Li Si", "Xiao Ming"]
  10. console.log(arr); // ["Zhang San", "Xiao Hong"]
  11. /**************Add "Xiaogang"****************/
  12. var arrReplace3 = arr.splice( 1, 0, "Xiao Gang");
  13. console.log(arrReplace3); // [] (no element was deleted, so an empty array was returned)
  14. console.log(arr); // ["Zhang San", "Xiao Gang", "Xiao Hong"]
  15. //Add multiple
  16. var arrReplace4 = arr.splice( 3, 0, "Liu Yi", "Chen er", "Zhao Liu");
  17. console.log(arrReplace4); // []
  18. console.log(arr); // ["Zhang San", "Xiao Gang", "Xiao Hong", "Liu Yi", "Chen Er", "Zhao Liu"]
  19. /**************"Wang Wu "replaces" Xiao Gang "****************/
  20. var arrReplace5 = arr.splice( 1, 1, "Wang Wu");
  21. console.log(arrReplace5); // ["Xiaogang"]
  22. console.log(arr); // ["Zhang San", "Wang Wu", "Xiao Hong", "Liu Yi", "Chen Er", "Zhao Liu"]
  23. //Replace multiple
  24. var arrReplace6 = arr.splice( 1, 4, "Li Si");
  25. console.log(arrReplace6); // ["Wang Wu", "Xiao Hong", "Liu Yi", "Chen Er"]
  26. console.log(arr); // ["Zhang San", "Li Si", "Zhao Liu"]
  27. </script>

Adding method of ES5 array:

Two index methods: indexOf() and lastIndexOf()

Both methods return the position where the item to be found first appears in the array, and - 1 if it is not found

indexOf()--------array.indexOf(item,start) (search backward from the beginning of the array (position 0))

item: required. Find the element.

Start: optional integer parameter. Specifies where to start retrieval in the array. If this parameter is omitted, the retrieval will start from array[0].

lastIndexOf()--------array.lastIndexOf(item,start)

item: required. Find the element.

Start: optional integer parameter. Specifies where to start retrieval in the array. If this parameter is omitted, the retrieval will start from {array[array.length-1].

   
  1. <script>
  2. var arr = [ 1, 4, 7, 10, 7, 18, 7, 26];
  3. console.log(arr.indexOf( 7)); // 2
  4. console.log(arr.lastIndexOf( 7)); // 6
  5. console.log(arr.indexOf( 7, 4)); // 4
  6. console.log(arr.lastIndexOf( 7, 2)); // 2
  7. console.log(arr.indexOf( 5)); // -1
  8. </script>

Five iterative methods: forEach(), map(), filter(), some(), every()

The syntax of these methods is the same, and none of them will change the original array.

forEach(): loop through the array. This method does not return a value. jquery() also provides the corresponding method, each().

Syntax: array forEach(function(currentValue , index , arr){//do something}, thisValue)

currentValue: required. Current element

Index: optional. The index value of the current element.

arr: optional. The array object to which the current element belongs.

thisValue: optional. The value passed to the function is generally "this". If this parameter is empty, "undefined" is passed to the "this" value

   
  1. <script>
  2. var Arr = [ 1, 4, 7, 10];
  3. Arr.forEach( function(currentValue, index, arr){
  4. console.log(index+ "--"+currentValue+ "--"+(arr === Arr));
  5. })
  6. // Output:
  7. // 0--1--true
  8. // 1--4--true
  9. // 2--7--true
  10. // 3--10--true
  11. </script>

map(): refers to "mapping". The method returns a new array. The elements in the array are the values of the original array elements after calling the function.

Syntax: array map(function(currentValue , index , arr){//do something}, thisValue)  

The map method squares each number in the array:

   
  1. <script>
  2. var arr = [ 1, 4, 8, 10];
  3. var arr2 = arr.map( function(currentValue){
  4. return currentValue*currentValue;
  5. });
  6. console.log(arr2); // [1, 16, 64, 100]
  7. </script>

filter(): "filter" function. The method creates a new array containing all the elements of the test implemented by the provided function. Similar to the filter() method, there is a grep() method in jquery, which is also used for filtering array elements.

Syntax: array filter(function(currentValue , index , arr){//do something}, thisValue) 

The filter method filters out all elements less than 5:

   
  1. <script>
  2. var arr = [ 1, 4, 6, 8, 10];
  3. var result1 = arr.filter( function(currentValue){
  4. return currentValue> 5;
  5. });
  6. console.log(result1); // [6, 8, 10]
  7. var result2 = arr.filter( function(currentValue){
  8. return currentValue> "5";
  9. });
  10. console.log(result2); // [6, 8, 10]
  11. </script>

When we set item > 5 and item > "5" respectively, the returned results are the same. Therefore, we can see that the function supports weak equals (= =), not all (= =).

every(): judge whether each item in the array meets the conditions. true will be returned only if all items meet the conditions.

Syntax: array every(function(currentValue , index , arr){//do something}, thisValue) 

   
  1. <script>
  2. var arr = [ 1, 4, 6, 8, 10];
  3. var result1 = arr.every( function(currentValue){
  4. return currentValue< 12;
  5. });
  6. console.log(result1); // true
  7. var result2 = arr.every( function(currentValue){
  8. return currentValue> 1;
  9. });
  10. console.log(result2); // false
  11. </script>

some(): judge whether there are items that meet the conditions in the array. As long as one item meets the conditions, it will return true.

Syntax: array some(function(currentValue , index , arr){//do something}, thisValue)

   
  1. <script>
  2. var arr = [ 1, 4, 6, 8, 10];
  3. var result1 = arr.some( function(currentValue){
  4. return currentValue> 10;
  5. });
  6. console.log(result1); // false
  7. var result2 = arr.some( function(currentValue){
  8. return currentValue> 5;
  9. });
  10. console.log(result2); // true
  11. </script>

Two merging methods: reduce() and reduceRight()

Both methods iterate over all the items in the array and then generate a final return value. They all receive two parameters. The first parameter is the function called by each item. The function accepts four parameters: initial value, current value, index value, and current array. The function needs to return a value, which will be used as the initial value in the next iteration. The second parameter is the iterative initial value. The parameter is optional. If it is the default, the initial value is the first item of the array, which is superimposed from the first item of the array. The default parameter needs one operation less than the normal value transfer.

The reduce() method starts from the first item of the array and traverses one by one to the end. Reducereight() starts from the last item of the array and traverses forward to the first item.

reduce() syntax: arr.reduce (function (total, cur, index, ARR) {/ / do something}, initialvalue)

reduceRight() syntax: arr.reduceright (function (total, cur, index, ARR) {/ / do something}, initialvalue)

total: required. Initial value, or return value after calculation.

cur: required. Current element.

Index: optional. The index of the current element.

arr: optional. The array object to which the current element belongs.

initialValue: optional. The initial value passed to the function.

The following code implements array summation:

   
  1. <script>
  2. var arr = [ 1, 2, 3, 4, 5];
  3. var result1 = arr.reduce( function(total,cur,index,arr){
  4. console.log( "total:"+total+ ",cur:"+cur+ ",index:"+index);
  5. return total+cur;
  6. });
  7. console.log( "result:"+result1);
  8. // output
  9. // total:1,cur:2,index:1
  10. // total:3,cur:3,index:2
  11. // total:6,cur:4,index:3
  12. // total:10,cur:5,index:4
  13. // Result: 15
  14. var result2 = arr.reduce( function(total,cur,index,arr){
  15. console.log( "total:"+total+ ",cur:"+cur+ ",index:"+index);
  16. return total+cur;
  17. }, 10);
  18. console.log( "result:"+result2);
  19. // output
  20. // total:10,cur:1,index:0
  21. // total:11,cur:2,index:1
  22. // total:13,cur:3,index:2
  23. // total:16,cur:4,index:3
  24. // total:20,cur:5,index:4
  25. // Result: 25
  26. </script>

From the above code, we can see that when we do not pass the iterative initial value to the function, the initial value ^ total is the first item of the array, and the function iterates from the second item of the array; If we pass the initial value of the iteration to the function, the function iterates from the first item of the array.

New method for ES6 array (note browser compatibility)

1.Array.from()

The method is used to convert array like objects (that is, objects with length attribute) and traversable objects into real arrays.

   
  1. <script>
  2. let json ={
  3. '0': 'Lu',
  4. '1': 'book',
  5. '2': 'Great',
  6. length: 3
  7. }
  8. let arr = Array.from(json);
  9. console.log(arr); // ["Lu", "Ben", "Wei"]
  10. </script>

2.Array.of()

The method is to convert a set of values into an array. The parameters are not divided into types, but only fractional quantities. If the quantity is 0, an empty array is returned.

   
  1. <script>
  2. let arr1 = Array.of( 1, 2, 3);
  3. let arr2 = Array.of([ 1, 2, 3]);
  4. let arr3 = Array.of( undefined);
  5. let arr4 = Array.of();
  6. console.log(arr1); // [1, 2, 3]
  7. console.log(arr2); // [[1, 2, 3]]
  8. console.log(arr3); // [undefined]
  9. console.log(arr4); // []
  10. </script>

3.find()

Method returns the value of the first element of the array that passes the test (judgment within the function). The method calls the function execution once for each element in the array. When the element in the array returns true when testing the condition, find() returns the qualified element, and the subsequent value will not call the execution function again. undefined if there are no qualified elements.

The callback function can receive three parameters, namely, the current value (currentValue), the current position (index) and the original array (arr)

Note: the find() function does not execute for empty arrays. Find () does not change the original value of the array.

   
  1. <script>
  2. let Arr = [ 1, 2, 5, 7, 5, 9];
  3. let result1 = Arr.find( function(currentValue,index,arr){
  4. return currentValue> 5;
  5. });
  6. let result2 = Arr.find( function(currentValue,index,arr){
  7. return currentValue> 9;
  8. });
  9. console.log(result1); // 7
  10. console.log(result2); // undefined
  11. </script>

The find() implementation takes out the objects in the array according to the id

   
  1. <script>
  2. let Arr = [
  3. {
  4. id: 1,
  5. name: "Zhang San"
  6. },
  7. {
  8. id: 2,
  9. name: "Li Si"
  10. }
  11. ];
  12. let obj = Arr.find( function(currentValue,index,arr){
  13. return currentValue.id=== 1;
  14. });
  15. console.log(obj.name); // Zhang San
  16. </script>

4.findIndex ()

findIndex is similar to find, but it returns the index by default. If there are no qualified elements, it returns - 1

   
  1. <script>
  2. let Arr = [ 1, 2, 5, 7, 5, 9];
  3. let result1 = Arr.findIndex( function(currentValue,index,arr){
  4. return currentValue> 5;
  5. });
  6. let result2 = Arr.findIndex( function(currentValue,index,arr){
  7. return currentValue> 9;
  8. });
  9. console.log(result1); // 3
  10. console.log(result2); // -1
  11. </script>

5.fill()

The fill() method fills all the elements in an array from the start index to the end index with a fixed value. Index termination is not included.

Syntax: array fill(value,  start,  end)

Value: required. The value of the padding.

start: optional. start filling position. If this parameter is negative, it specifies that it starts from the end of the array.

End: optional. Stop filling position (default = array.length). If this parameter is negative, it specifies that it starts from the end of the array.

   
  1. <script>
  2. let arr = [ 1, 2, 3, 4, 5, 6];
  3. arr.fill( 0); // [0, 0, 0, 0, 0, 0]
  4. arr.fill( 0, 1); // [1, 0, 0, 0, 0, 0]
  5. arr.fill( 0, 1, 2); // [1, 0, 3, 4, 5, 6]
  6. arr.fill( 0, -1); // [1, 2, 3, 4, 5, 0]
  7. arr.fill( 0, 1, -1); // [1, 0, 0, 0, 0, 6]
  8. </script>

6. Traverse the array methods keys(), values(), and entries()

These three methods all return an ergodic object, which can be used for Of loop traversal. The only difference is that keys() traverses key names, values() traverses key values, and entries() traverses key value pairs.

keys()

   
  1. <script>
  2. let arr = [ "a", "b", "c", "d"];
  3. for( let i of arr.keys()){
  4. console.log(i);
  5. }
  6. //Print:
  7. // 0
  8. // 1
  9. // 2
  10. // 3
  11. </script>

values()

   
  1. <script>
  2. let arr = [ "a", "b", "c", "d"];
  3. for( let i of arr.values()){
  4. console.log(i);
  5. }
  6. //Print:
  7. // a
  8. // b
  9. // c
  10. // d
  11. </script>

entries()

   
  1. <script>
  2. let arr = [ "a", "b", "c", "d"];
  3. for( let i of arr.entries()){
  4. console.log(i);
  5. }
  6. //Print:
  7. // [0, "a"]
  8. // [1, "b"]
  9. // [2, "c"]
  10. // [3, "d"]
  11. for( let [idx,item] of arr.entries()){
  12. console.log(idx+ ":"+item);
  13. }
  14. //Print:
  15. // 0:a
  16. // 1:b
  17. // 2:c
  18. // 3:d
  19. </script>

7.includes()

Method is used to determine whether an array contains a specified value. If yes, it returns true; otherwise, it returns false.

Syntax: arr.includes(searchElement, fromIndex)

searchElement: required. The element value to find.

fromIndex: optional. Search for searchElement starting at this index. If it is a negative value, it is from array. In ascending order Start the search with the index of length + fromIndex. The default is 0.

   
  1. <script>
  2. let arr = [ "a", "b", "c", "d"];
  3. let result1 = arr.includes( "b");
  4. let result2 = arr.includes( "b", 2);
  5. let result3 = arr.includes( "b", -1);
  6. let result4 = arr.includes( "b", -3);
  7. console.log(result1); // true
  8. console.log(result2); // false
  9. console.log(result3); // flase
  10. console.log(result4); // true
  11. </script>

8.copyWithin()

Method is used to copy elements from the specified location of the array to another specified location of the array, overwriting the original members

Syntax: array copyWithin(target ,  start ,  end)

target: required. Replace data from this location.

start: optional. start reading data from this location. The default is 0. If it is negative, it indicates the reciprocal.

end: optional. Stop reading data before reaching this position. By default, it is equal to the length of the array. If it is negative, it indicates the reciprocal.

   
  1. <script>
  2. let arr = [ 1, 2, 3, 4, 5, 6];
  3. let result1 = [ 1, 2, 3, 4, 5, 6].copyWithin( 0);
  4. let result2 = [ 1, 2, 3, 4, 5, 6].copyWithin( 0, 1);
  5. let result3 = [ 1, 2, 3, 4, 5, 6].copyWithin( 1, 3, 5);
  6. let result4 = [ 1, 2, 3, 4, 5, 6].copyWithin( 1, 2, -1);
  7. let result5 = [ 1, 2, 3, 4, 5, 6].copyWithin( 1, -4, 6);
  8. console.log(result1); // [1, 2, 3, 4, 5, 6]
  9. console.log(result2); // [2, 3, 4, 5, 6, 6]
  10. console.log(result3); // [1, 4, 5, 4, 5, 6]
  11. console.log(result4); // [1, 3, 4, 5, 5, 6]
  12. console.log(result5); // [1, 3, 4, 5, 6, 6]
  13. </script>

 

Original link: https://blog.csdn.net/qq_39132756/article/details/85007082

Topics: Javascript array