Home >Web Front-end >JS Tutorial >How to delete specified elements from a javascript array
Javascript method to delete specified elements in an array: 1. Use the delete keyword, the syntax format "delete array[array subscript]"; 2. Use the splice() function, the syntax format "array.splice(array Subscript,1)”.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript comes with methods to delete array elements:
1.delete method
delete After deleting the elements in the array, the subscripted value will be set to undefined, and the length of the array will not change
For example:
delete arr[1] //[‘a’, ,‘c’,‘d’] 中间出现两个逗号,数组长度不变,有一项为undefined
2.splice method
The splice() method is used to add or remove elements from an array.
Note: This method will change the original array.
Return value: If the array element is deleted, the array containing the deleted element is returned. If only one element is deleted, an array of one element is returned. If no elements were removed, an empty array is returned.
Example:
//获取元素在数组的下标 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 start index
len: The length of replacement/deletion
item: The value of replacement, if the deletion operation occurs, the item is empty
For example:
arr = [‘a’,‘b’,‘c’,‘d’]
Delete ---- item is not set
arr.splice(1,1) //[‘a’,‘c’,‘d’] 删除起始下标为1,长度为1的一个值,len设置的1,如果为0,则数组不变 arr.splice(1,2) //[‘a’,‘d’] 删除起始下标为1,长度为2的一个值,len设置的2
Replace ---- item is the replaced value
arr.splice(1,1,‘ttt’) //[‘a’,‘ttt’,‘c’,‘d’] 替换起始下标为1,长度为1的一个值为‘ttt’,len设置的1 arr.splice(1,2,‘ttt’) //[‘a’,‘ttt’,‘d’] 替换起始下标为1,长度为2的两个值为‘ttt’,len设置的1
Add ---- len Set to 0, item is the added value
arr.splice(1,0,‘ttt’) //[‘a’,‘ttt’,‘b’,‘c’,‘d’] 表示在下标为1处添加一项‘ttt’
[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!