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>
登录后复制

效果图:

js怎么使用pop()和shift()来删除数组元素?(代码实例)-LMLPHP

注:数组.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>
登录后复制

代码实例:

js怎么使用pop()和shift()来删除数组元素?(代码实例)-LMLPHP

以上就是本篇文章所介绍的在js数组中添加元素的三种方法,分别是pop()和shift()。工作中选择哪种方法,看工作需要和个人习惯, 小白可以自己动手尝试,加深理解,希望这篇文章可以帮助到你!更多相关教程请访问:JavaScript视频教程jQuery视频教程bootstrap视频教程

以上就是js怎么使用pop()和shift()来删除数组元素?(代码实例)的详细内容,更多请关注Work网其它相关文章!

09-18 11:23