在Javascript/jQuery中从数组中删除多个元素 [英] Remove multiple elements from array in Javascript/jQuery

查看:116
本文介绍了在Javascript/jQuery中从数组中删除多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组.第一个数组包含一些值,而第二个数组包含应从第一个数组中删除的值的索引.例如:

I have two arrays. The first array contains some values while the second array contains indices of the values which should be removed from the first array. For example:

var valuesArr = new Array("v1","v2","v3","v4","v5");   
var removeValFromIndex = new Array(0,2,4);

我想从valuesArr中删除索引0,2,4处的值.我认为本机splice方法可能会有所帮助,所以我想到了:

I want to remove the values present at indices 0,2,4 from valuesArr. I thought the native splice method might help so I came up with:

$.each(removeValFromIndex,function(index,value){
    valuesArr.splice(value,1);
});

但是它不起作用,因为在每个splice之后,valuesArr中的值的索引是不同的.我可以通过使用临时数组并将所有值复制到第二个数组来解决此问题,但是我想知道是否有本机方法可以传递多个索引以从数组中删除值.

But it didn't work because after each splice, the indices of the values in valuesArr were different. I could solve this problem by using a temporary array and copying all values to the second array, but I was wondering if there are any native methods to which we can pass multiple indices at which to remove values from an array.

我更喜欢jQuery解决方案. (不确定我是否可以在此处使用grep)

I would prefer a jQuery solution. (Not sure if I can use grep here)

推荐答案

总是存在普通的for循环:

var valuesArr = ["v1","v2","v3","v4","v5"],
    removeValFromIndex = [0,2,4];    

for (var i = removeValFromIndex.length -1; i >= 0; i--)
   valuesArr.splice(removeValFromIndex[i],1);

以相反的顺序浏览removeValFromIndex,您可以.splice()而不弄乱尚未删除的项目的索引.

Go through removeValFromIndex in reverse order and you can .splice() without messing up the indexes of the yet-to-be-removed items.

在上面的说明中,我使用了带有方括号的array-literal语法来声明两个数组.这是推荐的语法,因为new Array()的使用可能会造成混淆,因为它会根据您传入的参数的多少而做出不同的响应.

Note in the above I've used the array-literal syntax with square brackets to declare the two arrays. This is the recommended syntax because new Array() use is potentially confusing given that it responds differently depending on how many parameters you pass in.

编辑:刚刚看到您对另一个答案的评论,该答案不一定是按特定顺序排列的索引数组.如果是这种情况,请在开始之前按降序对其进行排序:

EDIT: Just saw your comment on another answer about the array of indexes not necessarily being in any particular order. If that's the case just sort it into descending order before you start:

removeValFromIndex.sort(function(a,b){ return b - a; });

然后按照您喜欢的任何循环/$.each()/等方法进行操作.

And follow that with whatever looping / $.each() / etc. method you like.

这篇关于在Javascript/jQuery中从数组中删除多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆