Common array operation methods in JavaScript

Posted by paruby on Sat, 13 Nov 2021 03:01:04 +0100

1,concat()
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.

2,join()
The join() method is used to put all the elements in the array into a string. Elements are separated by the specified separator. By default, they are separated by ',' and do not change the original array.

3,push()
The push() method adds one or more elements to the end of the array and returns a new length. Adding at the end returns the length, which will change the original array.

4,pop()
The pop() method is used to delete and return the last element of the array. Returning the last element changes the original array.

5,shift()
The shift() method removes the first element of the array from it and returns the value of the first element. Return the first element and change the original array.

6,unshift()
The unshift() method adds one or more elements to the beginning of the array and returns a new length. Return the new length and change the original array.
7,slice()
Returns a new array containing the elements in the arrayObject from start to end (excluding this element). Returns the selected element, which does not modify the original array.

8,splice()
The splice() method deletes zero or more elements starting at index and replaces those deleted elements with one or more values declared in the parameter list. If an element is deleted from an arrayObject, an array containing the deleted element is returned. The splice() method modifies the array directly.
9. substring() and substr()
The same point: if you just write a parameter, the functions of both are the same: they are the string fragments that intercept the string from the current subscript to the end of the string.
substr(startIndex);
substring(startIndex);

Difference: second parameter
substr (startIndex,lenth): the second parameter is the length of the intercepted string (intercepting a string of a certain length from the starting point);
substring (startIndex, endIndex): the second parameter is to intercept the final subscript of the string (intercept the string between two positions, 'including head and not including tail').

10. Sort sort
Sort by Unicode code position, ascending by default

11,reverse()
The reverse() method is used to reverse the order of the elements in the array. The returned array is the inverted array, which will change the original array

12. indexOf and lastIndexOf
Both accept two parameters: the value of the lookup and the starting position of the lookup
If it does not exist, return - 1; Exists, return to location. indexOf refers to searching from front to back, and lastIndexOf refers to searching from back to front.
indexOf

13,every
Run the given function on each item of the array, and return true if each item returns true

14,some
Run the given function on each item of the array. If any item returns true, it returns true

15,filter
Run the given function on each item of the array and return an array of items with the result of true

16,map
Run the given function on each item of the array and return the result of each function call to form a new array

17. forEach array traversal

js deletes an element in the array
How to delete an element of an array in JavaScript? We need to understand the method of splice, which is translated as splicing. arr.splice(0,1) means to delete the first element of the array, and arr.splice(1,2) means to delete 2 elements starting from the second element.

Deletes an element specified in the array
First, you can define a function for the array object of js to find the position of the specified element in the array, that is, the index. The code is:

Array.prototype.indexOf = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};

Then, by obtaining the index of this element, use the inherent function of js array to delete this element: the code is:

Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};

This constructs such a function. For example, I have an array:

var emp = ['abs','dsf','sdf','fd']

If we want to delete 'fd', we can use:

emp.remove('fd');

Delete an item of the array
splice(index,len,[item]) Note: this method will change the original array. splice has three parameters. It can also be used to replace / delete / add one or more values in the array. Index: array start subscript len: length of replacement / deletion item: value of replacement. In case of deletion, the item is empty, such as: arr = ['a', 'b', 'c','d '] delete

//Delete a value with a starting subscript of 1 and a length of 1 (len is set to 1. If it is 0, the array remains unchanged)
var arr = ['a','b','c','d'];
arr.splice(1,1);
console.log(arr);  
//['a','c','d']; 

//Delete a value with a starting subscript of 1 and a length of 2 (len set to 2)
var arr2 = ['a','b','c','d']
arr2.splice(1,2);
console.log(arr2); 
//['a','d']

replace

//Replace a value with a starting subscript of 1, a length of 1 as' ttt ', and a value set by len as 1
var arr = ['a','b','c','d'];
arr.splice(1,1,'ttt');
console.log(arr);        
//['a','ttt','c','d'] 

var arr2 = ['a','b','c','d'];
arr2.splice(1,2,'ttt');
console.log(arr2);       
//['a','ttt','d'] replace the two values with the starting subscript of 1 and the length of 2 as' ttt ', and the 1 set by len

Add - set len to 0 and item to the added value

var arr = ['a','b','c','d'];
arr.splice(1,0,'ttt');
console.log(arr);        
//['a','ttt','b','c','d '] indicates that an item' ttt 'is added at the subscript 1

Javascript method to delete the specified element in the array

  1. splice() function

splice() is probably the most powerful array method. It has many uses. Here we only introduce the method of deleting array elements. When deleting an array element, it can delete any number of items. Only two parameters need to be specified: the position of the first item to be deleted and the number of items to be deleted. For example, splice (0,2) will delete the first two items in the array.

var colors = ["red", "blue", "grey"];
var item = colors.splice(0, 1);
console.log(item);      //"red"
console.log(colors);    //["blue", "grey"]

The iterative method deletes the specified element in the array

The so-called iterative method is to iterate the array elements in a loop, and delete the items that match the items to be deleted. The most frequently used place may be when the elements in the array are objects, and delete the array elements according to the attributes of the object, such as ID, etc. Two methods are described below:

The first method uses the most common ForEach loop to compare elements and delete them after finding them:

var colors = ["red", "blue", "grey"];

colors.forEach(function(item, index, arr) {
    if(item == "red") {
        arr.splice(index, 1);
    }
});

Second, we use the filter method in the loop

var colors = ["red", "blue", "grey"];

colors = colors.filter(function(item) {
    return item != "red"
});
console.log(colors);    //["blue", "grey"]

The code is very simple. Find out the number of items whose element is not "red" and return it to colors (in fact, you get a new array), so as to delete it.

delete keyword deletes a specified element in an array

var arr = [1, 2, 3, 4];
delete arr[0];
console.log(arr);   //[undefined, 2, 3, 4]

It can be seen that the array length remains unchanged after delete, but the deleted elements are set to undefined

  1. pop() method

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

var colors = ["red", "blue", "grey"];
var item = colors.pop();
console.log(item);      //"grey"
console.log(colors.length);    //2

It can be seen that when the Pop method is called, the array returns the last item, "grey", and there are only two elements left in the array.

  1. shift() method

Topics: Javascript Front-end ECMAScript array