本文由 DTcms素材网 – DT素材网 发布,转载请注明出处,如有问题请联系我们!js怎么使用pop()和shift()来删除数组元素?(代码实例)
收藏       js数组如何删除数组元素?本篇文章就给大家介绍js数组删除元素的方法,让大家了解js数组(一维)怎么使用pop()和shift()来删除元素。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。
                
            方法一:js数组使用pop()方法删除元素
pop()方法可以将数组最末尾的一个元素删除,并返回删除的元素值。注:数组的长度会改变,减 1。
说明:
如果数组已经为空,则 pop() 不改变数组,并返回 undefined 值。
代码实例:删除animal数组的最末尾的rabbit
<!DOCTYPE html> <html>  <head>   <meta charset="UTF-8">  </head>  <body>   <div class="demo">    <p>数组:cat,elephant,tiger,rabbit;<br>数组长度为:4</p>       <button onclick="myFunction()">点我--pop()删除元素</button>   </div>  </body>  <script type="text/javascript">   function myFunction(){      var animal = ["cat", "elephant", "tiger","rabbit"];      document.write("<p>数组:"+animal+"<br>数组长度:"+ animal.length+"</p>");      var animal1= animal.pop();      document.write("<p>新数组:"+animal+"<br>删除的元素为:"+ animal1+"<br>数组长度:"+ animal.length+"</p>");   }     </script> </html>
效果图:

注:数组.length返回数组长度。
方法二:js数组使用shift()方法删除元素
shift()方法可以将数组最开头的一个元素删除,并返回删除的元素值。注:数组的长度会改变,减 1。
代码实例:
<!DOCTYPE html> <html>  <head>   <meta charset="UTF-8">  </head>  <body>   <div class="demo">    <p>数组:cat,elephant,tiger,rabbit;<br>数组长度为:4</p>       <button onclick="myFunction()">点我--shift()删除元素</button>   </div>  </body>  <script type="text/javascript">   function myFunction(){      var animal = ["cat", "elephant", "tiger","rabbit"];      document.write("<p>数组:"+animal+"<br>数组长度:"+ animal.length+"</p>");      var animal1= animal.shift();      document.write("<p>新数组:"+animal+"<br>删除的元素为:"+ animal1+"<br>数组长度:"+ animal.length+"</p>");   }     </script> </html>
代码实例:



