根据索引值从 javascript 数组中删除特定项目
Removing specific items from a javascript array based on index values
假设我有一个像这样的简单 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] 之外的所有项目。我知道我可以使用 splice 像这样一块一块地做:
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()
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
The includes()
method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
演示:
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);
假设我有一个像这样的简单 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] 之外的所有项目。我知道我可以使用 splice 像这样一块一块地做:
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()
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
The
includes()
method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
演示:
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);