基于索引值从javascript数组中删除特定项



假设我有一个简单的javascript数组,如下所示:

var test_array  = ["18081163__,0,0.15,15238", "34035", "Somerset", "Local", "31221", "29640", "42575", "749", "1957", "45809", "17597", "43903", "1841", "1", "Norfolk Road", "Other"]

它的长度=16。我想删除除[0,2,3,14]之外的所有基于索引的项。我知道我可以用拼接来一块一块地做,就像这样:

test_array.splice(1,1);
test_array.splice(3, 10);
test_array.splice(4, 1);

如何在一行代码中删除索引为[1,4,5,6,7,8,9,10,11,12,13,15]的项目?

考虑您有一个索引数组,您想根据它删除项目,然后您可以尝试使用Array.prototype.filter()

filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

Array.prototype.includes()

includes()方法确定数组的条目中是否包含某个值,并根据情况返回true或false。

演示:

var test_array  = ["18081163__,0,0.15,15238", "34035", "Somerset", "Local", "31221", "29640", "42575", "749", "1957", "45809", "17597", "43903", "1841", "1", "Norfolk Road", "Other"];
var index = [1,4,5,6,7,8,9,10,11,12,13,15];
test_array = test_array.filter((item, idx) => !index.includes(idx)); //remove the items whose index does not include the index array
console.log(test_array);

最新更新