Array methods in Javascript summarize of recommendations

  • 2020-05-24 05:13:35
  • OfStack

Array.prototype defines a number of methods for manipulating arrays. Here are some of the methods in ECMAScript3

1. Array. join () method

This method converts all the elements of the array into strings and concatenates them to 1 by the specified symbol. The resulting string can contain one parameter, which is the symbol of concatenated array elements, and the default is comma.


var ay = [1,2,3];
ay.join();       // =>"1,2,3" 
ay.join("+");     // => "1+2+3" 
ay.join(" ");     // =>"1 2 3"
ay.join("");      // =>"123"

var by = new Array(10) // new 1 A length of 10 The empty array 
by.join("-");      //=> "---------"  The connection 10 Empty elements 

2. Array. reverse () method

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


var a = [1,2,3];
a.reverse().join();    //=>"3,2,1" , At this time 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 takes no arguments, the array is sorted alphabetically, and if the array contains undefined elements, it goes to the end of the array.


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

We can also pass in a comparison function as an argument to the sort() method and have the array sort with the specified comparison function. If the return value of the comparison function is less than 0, the first parameter is first; if the return value is greater than 0, the second parameter is first, and the two parameter values are equal, then 0 is returned


var sy = [1111,222,4,33];
sy.sort();                               //=>"1111,222,33,4"
sy.sort(function(a,b){
            return a-b;
});                                        //=> "4,33,222,1111"

Note: anonymous functions are best used here because they are called only once and do not require a function name

4. Array. concat () method

This method creates and returns a new array, concatenating the elements of the original array with each element in the method to form a new array. This method does not recursively call the arguments in the method.


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

5. Array. slice () method

This method returns a fragment or subarray of the specified array. This method can take two arguments, specifying the start and end positions of the fragment. The returned array contains the elements specified by the first argument and all the array elements to but not containing the locations specified by the second argument. If there is only one argument, the argument from the specified starting position to the end of the array can be negative, indicating the position relative to the last element in the array. This method does not modify the array being called.


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 way to insert or delete elements into an array, and it modifies the original array. This method can contain more than one parameter, the first parameter specifies to the original position of the insertion or deletion in the array, the second parameter set to delete the number of elements, if not specified will delete all starting position and the back element, the parameters of the two parameters specify the insertion of the array elements, this method returns the removed elements of the array.


var e = [1,2,3,4,5,6];
e.splice(4);          //=>  return [5,6] ; e is [1,2,3,4]
e.splice(1,2);         //=>  return [2,3] ; e is [1,4]
      
var f = [1,2,3,4,5];
f.splice(2,0,"a","b");   //=> return []; f is [1,2,a,b,3,4,5]
f.splice(2,2,[6,7],3);   //=> return [a,b]; f is [1,2,[6,7],3,4,5]

7.push() and pop() methods

The push() method adds one or more elements to the end of the array and returns the length of the array. The pop() method deletes the last element of the array, reduces the length of the array, and returns the deleted value.

8.unshift() method and shift() method

The unshift() method adds one or more elements to the head of the array and returns the length of the array. The shift() method deletes the first element of the array and returns it.


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

These two methods convert each element of the array to a string, and toString() converts each element to a string and separates the output with commas. The toLocaleString() method calls toLocaleString() to a string for each element of the array and concatenates it using a localization delimiter.

Here's a quick overview of some of the array methods that are unique to ECMAScript5. The first argument of most methods takes a function and calls it once for each element of the array. If the array is sparse, nonexistent elements do not call the function. In most cases, the called function takes three arguments: the array element, the index of the element, and the array itself.

1. forEach () method

This method traverses the array from beginning to end, with each element of the array calling the specified function. This method does not terminate until all the array elements have been traversed. To terminate early, you must put forEach() into an try block and can throw an exception.


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){ //=>3 Each parameter refers to an array element, an element index, and an array, 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 containing the return value of the array element calling the function. In the case of a sparse array, the new array returned is an array of coefficients of the same structure.


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, and the passed function is used for logical determination, returning true or false. If the returned value is true or can be converted to true, then the current array element is a member of the subset and is added to the returned array. This method skips the empty elements of a sparse array.


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 Representing element index 
  return i%2==0; 
})                         //=> return [5,3,1]


4.every() and some() methods

The two methods are to make a logical determination of the array, and return true or false for each element of the array using the specified function.
The every() method returns true if and only if all elements in the array call the decision function to return true, otherwise false.
The some() method returns true when at least one element in the array calls the decision function to return true, or false.

Both of these methods are 1. Once you confirm the return value, you no longer iterate over the group of elements.

5.reduce() and reduceRight() methods

The two methods combine the array elements using the specified function to generate a single value.
reduce() takes two arguments, the first being the operation function that performs the simplification combination, and the second the initial value of the combination. Unlike the previous methods, the usual three arguments (array element, element index, and array itself) are passed to the function as two to four arguments to the action function, with the first argument being the result of the calculated combination so far.
Calling the reduce() method without specifying an initial value for an empty array results in a type error exception.
The reduceRight() method works the same way as the reduce() method, except that it is processed by array index from high to low (i.e. merge from right to left)

6.indexOf() and lastIndexOf() methods

Both methods are used to search the entire array for a specific given value and return the index value of the first matched element, or -1.indexOf() is searched from beginning to end, while lastIndexOf() is searched from end to end.


Related articles: