Home > Article > Web Front-end > How to delete specified elements from a javascript array
Methods for deleting specified elements from a javascript array: 1. Delete the specified elements in the array through the "splice" method; 2. Delete the elements in the array through the "delete" method.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
js array deletes specified elements
js comes with methods to delete elements:
1.splice method
//获取元素在数组的下标 Array.prototype.indexOf = function(val) { for (var i = 0; i < this.length; i++) { if (this[i] == val){ return i; }; } return -1; }; //根据数组的下标,删除该下标的元素 Array.prototype.remove = function(val) { var index = this.indexOf(val); if (index > -1) { this.splice(index, 1); } }; //测试数据 var insertAttaList = ['abs','dsf',,'abc','sdf','fd']; insertAttaList.remove('abc');
splice( index,len,[item]) Note: This method will change the original array.
splice has 3 parameters, it can also be used to replace/delete/add one or several values in the array
index: array starting subscript len: replacement/delete length item : Replacement value. If the operation is deleted, the item will be empty.
For example: arr = ['a','b','c','d']
Delete---- item Do not set
arr.splice(1,1) //['a','c','d'] Delete a value with a starting subscript of 1, a length of 1, and 1 set by len , if it is 0, the array remains unchanged
arr.splice(1,2) //['a','d'] Delete a value with a starting subscript of 1 and a length of 2, len The set 2
replacement---- item is the replaced value
arr.splice(1,1,'ttt') //['a','ttt','c ','d'] Replace the starting subscript with 1, a value with length 1 as 'ttt', and len set as 1
arr.splice(1,2,'ttt') //[ 'a','ttt','d'] replace the starting subscript as 1, the two values of length 2 as 'ttt', 1
of the len setting is added---- len is set to 0, item is the added value
arr.splice(1,0,'ttt') //['a','ttt','b','c','d'] is represented below Add an item 'ttt' at the location marked 1
2.delete method
After delete deletes the element in the array, the value marked under the array will be set to undefined, the length of the array It will not change
For example: delete arr[1] //['a', ,'c','d'] Two commas appear in the middle, the length of the array remains unchanged, and one item is undefined
【Recommended learning: javascript advanced tutorial】
The above is the detailed content of How to delete specified elements from a javascript array. For more information, please follow other related articles on the PHP Chinese website!