簡體   English   中英

根據索引值從 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()

filter()方法創建一個新數組,其中包含通過提供的 function 實現的測試的所有元素。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM