删除数组中的一个元素的方法有很多种,例如可以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方法并没有改变原数组,而是把符合条件的元素推入了一个新数组。