Deleting specified elements from js arrays is a problem that each of us encounters. There is a lot of information on this aspect on the Internet, but some of it is too old and some of the content is not comprehensive enough, so I will sort it out myself. This article This article mainly summarizes and introduces various methods for deleting specific elements in JavaScript arrays. Friends in need can refer to it.
Preface
Maybe when it comes to deleting specific elements of an array, you estimate that there is more than one way to achieve it, so let’s take a look. Check out these methods I’ve summarized, they may be helpful to you! Not much to say, let’s take a look at the detailed introduction.
Source array
##
var arr = ["George", "John", "Thomas", "James", "Adrew", "Martin"];
Pseudo delete
arr[ arr.indexOf( 'Thomas' ) ] = null;
["George", "John", null, "James", "Adrew", "Martin"]
Complete deletion
Array.prototype.splice = function(start,deleteCount,items) {};
When the parameter is not added, it means deleting the element, and it must be combined with the parameter value of deleteCount
If deleteCount is 1 and a parameter value is given in the items parameter position, it means replacing
If deleteCount is 1 and the items parameter position is given to more than one parameter value, it means replacing and appending elements
arr.splice( arr.indexOf( null ), 1 );
["George", "John", "James", "Adrew", "Martin"]
splice function - replace elements
["George", "John", "James", "Adrew", "Martin"]
##
arr.splice( arr.indexOf( 'James' ), 1, 'Tom' );
["George", "John", "Tom", "Adrew", "Martin"]
Now the current array structure is like this:
["George", "John", "Tom", "Adrew", "Martin"]
arr.splice( arr.indexOf( 'Tom' ), 1, 'Judy', 'Linda', 'Alisa' );
["George", "John", "Judy", "Linda", "Alisa", "Adrew", "Martin"]
You can choose to append elements Any position depends on your specific needs. The key lies in the value index position of start! The current array structure is as follows:
["George", "John", "Judy", "Linda", "Alisa", "Adrew", "Martin"]
arr.splice( arr.indexOf( 'Linda' ) + 1, 0, 'Bill', 'Blake' );
["George", "John", "Judy", "Linda", "Bill", "Blake", "Alisa", "Adrew", "Martin"]
is after the array element Linda
Delete the first element in the array
arr.shift();
The deleted array looks like this:
["John", "Judy", "Linda", "Bill", "Blake", "Alisa", "Adrew", "Martin"]
arr.pop();
The deleted array looks like this:
["John", "Judy", "Linda", "Bill", "Blake", "Alisa", "Adrew"]
The above is the detailed content of Introduction to methods of deleting specific elements from JavaScript arrays. For more information, please follow other related articles on the PHP Chinese website!