用indexOf, splice删除数组中的一个元素

删除数组中的一个元素的方法有很多种,例如可以for循环把不要删除的元素推入一个新数组,也可以不用for循环,用indexOf 和splice方法来配合,代码如下:

<html>

<head>
<style type="text/css">

</style>
</head>

<body>


<script>

var arr = ["abd", "def", "ghi", "opq"];

function remove(arr, item){
	if(!arr.length){
		console.error("arr is empty");
		return;
	}
	var index = arr.indexOf(item);
	if(index > -1){
		arr.splice(index, 1);
	}	
}

console.log("arr remove before: " + arr);
remove(arr, "ghi");
console.log("arr remove after: " + arr);

</script

</body>
</html>

打印如下:

arr remove before: abd,def,ghi,opq
arr remove after: abd,def,opq

从打印看出把原数组arr中的ghi元素给删除了。

当然我们可以用ES6提供的数组filter方法,用法如下:

<html>

<head>
<style type="text/css">

</style>
</head>

<body>


<script>

var arr = ["abd", "def", "ghi", "opq"];

function remove(arr, item){
	return arr.filter(function(value, index){
		console.log("value is: " + value);
		console.log("index is: " + index);
		return value !==  item;
	});
}

console.log("arr remove before: " + arr);
var arrNew = remove(arr, "ghi");
console.log("arr remove after: " + arr);
console.log("arrNew: " + arrNew);

</script

</body>
</html>

打印如下:

从打印看出也实现了同样的效果,但filter方法并没有改变原数组,而是把符合条件的元素推入了一个新数组。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值