JS數組是開發中常用的數據結構,也是使用頻率比較高的一種數據類型。當我們需要處理數組的刪除操作時,JS提供了多種方法來實現。本文將從多個方面對JS數組刪除多個元素進行詳細闡述。
一、splice()方法
splice()方法可以刪除數組中的元素,並向數組添加新元素。它的語法如下:
array.splice(start, deleteCount, item1, item2, ...)
其中,start表示要刪除元素的起始位置索引,deleteCount表示要刪除元素的數量。如果想要添加新元素可以在splice()後面跟上要添加的新元素。
示例代碼:
let fruits = ['banana', 'apple', 'orange', 'grapefruit']; // 刪除1個元素 fruits.splice(2, 1); console.log(fruits); // ['banana', 'apple', 'grapefruit'] // 刪除2個元素,並添加2個新元素 fruits.splice(1, 2, 'cherry', 'lemon'); console.log(fruits); // ['banana', 'cherry', 'lemon', 'grapefruit']
二、filter()方法
filter()方法可以返回一個新數組,並且該數組包含所有通過指定函數過濾的元素。其中,指定函數需要返回一個布爾值來指示每個元素是否應該被返回到新數組中。如果返回true則包含在新數組中,否則不包含。
當需要同時刪除多個元素時,可以利用filter()方法來實現,代碼如下:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let toBeDeleted = [3, 5, 7]; let filtered = numbers.filter(e => !toBeDeleted.includes(e)); console.log(filtered); // [1, 2, 4, 6, 8, 9]
三、for循環操作
在JS中,我們可以通過for循環來遍曆數組,找到需要刪除的元素,並移除它們。具體實現代碼如下:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let toBeDeleted = [3, 5, 7]; for (let i = numbers.length - 1; i >= 0; i--) { if (toBeDeleted.includes(numbers[i])) { numbers.splice(i, 1); } } console.log(numbers); // [1, 2, 4, 6, 8, 9]
四、set結構
JS中的Set結構可以去重並保存沒有重複值的數組,可以利用它來操作數組刪除。
示例代碼如下:
let numbers = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]); let toBeDeleted = [3, 5, 7]; toBeDeleted.forEach(e => { numbers.delete(e); }); console.log(numbers); // Set {1, 2, 4, 6, 8, 9}
五、lodash庫中的_.without()方法
lodash庫是JS的一個實用工具庫,它提供了很多常用的工具函數。其中,_.without()方法可以用於從數組中刪除指定的元素,並返回新的數組。
示例代碼如下:
let _ = require('lodash'); let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let toBeDeleted = [3, 5, 7]; let filtered = _.without(numbers, ...toBeDeleted); console.log(filtered); // [1, 2, 4, 6, 8, 9]
六、總結
本文介紹了JS數組刪除多個元素的多種方法,包括splice()方法、filter()方法、for循環操作、set結構以及lodash庫中的_.without()方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/306230.html