JavaScript如何从数组中删除空元素?

JavaScript中为了从数组中删除空元素,可以使用filter()方法。filter()方法将返回一个新数组,其中包含传递回调函数条件的元素。

array.filter()方法从给定数组中创建一个新数组,该数组由所提供数组中满足参数函数条件的元素组成。

array.filter( function(cValue, index, arr), tValue )

参数:filter()方法接受下面列出的两个参数

● function:它包含三个参数

  ● cValue:此参数是必需的,它是当前元素的值。

  ● index:该参数是可选的,它是当前元素的数组索引。

  ● arr:此参数是可选的,它是当前元素所属的数组对象。

● tValue:此参数是可选的,该值将传递给函数以用作其“this”值。如果为空,则将传递值“undefined”。

示例:从数组中删除undefined,null和empty元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
	</head>
	<body style="text-align:center;">
		<p id="up"></p>
		<p id="down" style="color:green;"></p>
		<script>
			var array = ["a", "b", null, "c",
				"", "d", undefined, "e", , , , , ,
				"f", , 4, , 5, , 6, , , ,
			];

			var p_up = document.getElementById("up");

			p_up.innerHTML = "原数组:" + array;

			var p_down = document.getElementById("down");
			var filtered = array.filter(function(el) {
				return el != null;
			});
			p_down.innerHTML = "去除空元素的数组:" + filtered;
		</script>
	</body>

</html>

示例2:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
	</head>
	<body style="text-align:center;">
		<p id="up"></p>
		<p id="down"></p>
		<script>
			var array = ["a", "b", null, "c",
				"", "d", undefined, "e", , , , , ,
				"f", , 4, , 5, , 6, , , ,
			];

			var p_up = document.getElementById("up");

			p_up.innerHTML = "原数组:" + array;

			var p_down = document.getElementById("down");
			var filtered = array.filter(function(el) {
				return el;
			});
			p_down.innerHTML = "去除空元素的数组:" + filtered;
		</script>
	</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值