Home >Web Front-end >JS Tutorial >JavaScript: Delete array elements

JavaScript: Delete array elements

高洛峰
高洛峰Original
2016-11-25 11:21:57899browse

JavaScript truncates an array by setting the length property of the array is the only way to shorten the length of the array. If you use the delete operator to delete an element in the array, although that element becomes undefined, the length property of the array does not change. Two methods to delete elements and change the length of the array.

<script> <br> /*<br> * Method: Array.remove(dx)<br> * Function: delete array elements. <br> * Parameter: dx subscript of the deleted element. <br> * Return: modify the array on the original array<br> */</p> <p> //Often used is to reconstruct the array through traversal.<br> Array.prototype.remove=function(dx)<br> {<br> if(isNaN(dx)||dx&gt ;this.length){return false;}<br> for(var i=0,n=0;i<this.length;i++)<br/> {<br/> if(this[i]!=this[dx])<br/> {<br/> this [n++]=this[i]<br/> }<br/> }<br/> this.length-=1<br/> }<br/> a = [1,2,3,4,5];<br/> alert("elements: "+a+" Length: "+ a.length);<br/> a.remove(0); //Delete the element with index 0<br/> alert("elements: "+a+" Length: "+a.length);</p><p> /*<br/> * Method: Array .baoremove(dx)<br/> * Function: delete array element.<br/> * Parameter: dx subscript of deleted element.<br/> * Return: modify the array on the original array.<br/> */</p><p> //We can also use splice to achieve this.</p> <p> Array.prototype.baoremove = function(dx)<br/> {<br/> if(isNaN(dx)||dx>this.length){return false;}<br> this.splice(dx,1);<br> }<br> b = [1 ,2,3,4,5];<br> alert("elements: "+b+" Length: "+b.length);<br> b.baoremove(1); //Delete the element with subscript 1<br> alert(" elements: "+b+" Length: "+b.length);<br> </script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn