发布于 2026-01-06 0 阅读
0

JavaScript 中从数组中删除项目的现代方法 DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

JavaScript 中从数组中删除元素的现代方法

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

目录

  1. JavaScript 中的数组
  2. Array.prototype.shift()
  3. Array.prototype.pop()
  4. 删除运算符
  5. Array.prototype.splice()
  6. Array.prototype.filter()
  7. 一部杰作
  8. 结语

1. JavaScript 中的数组

JavaScript 中的数组是一种特殊的对象,它按顺序存储元素,也就是说,它们将元素一个接一个地存储在内存中。它们是高级的、类似列表的对象。实际上,你可以把它们看作是元素的列表。

数组中的每个元素都有一个索引,用于指示该元素在数组中的位置。第一个元素的索引为 0,下一个元素的索引为 1,依此类推。因此,JavaScript 的数组索引是从零开始的。
可以使用索引访问 JavaScript 数组中的元素。我们可以使用名为`indexOf`
的特殊方法来查找数组中元素的索引

你可以简单地把 JavaScript 数组理解为一个有序的值集合,你可以通过名称和索引来引用它。

const listOfAnimals = [ "dog", "cat", "rat", "fish", "rabbit" ] console.log(listOfAnimals) // returns the listOfAnimals array console.log(listOfAnimals[0]) // gets the item at index 0 console.log(listOfAnimals[2]) // gets the third item which is the item at index 2 let itemPosition = listOfAnimals.indexOf("rat") // gets the index of the item passed. here "rat" console.log(itemPosition) // displays the index of "rat" in the listOfAnimals array

数组中元素的总数等于该数组的长度。length
属性比较特殊,它总是返回最后一个元素的索引加一。

const evenNumbers = [2,4,6,8,10,12] console.log(evenNumbers.length) // returns the length of the evenNumbers array

JavaScript 数组是最常用的数据结构,由于它们按顺序组织元素,因此访问第一个和最后一个元素非常容易。所以,在 JavaScript 中删除这些元素也很容易。

2. Array.prototype.shift()

`shift ()`方法会移除数组中的第一个元素(即索引为 0 的元素)。它还会重新排列数组中剩余元素的顺序,并将数组长度减 1。最后,它会返回被移除的元素。

const languages = [ "PHP", "Python", "Rust", "C++", "C", "Ruby", "JavaScript" ] const removedLanguage = languages.shift() console.log(removedLanguage) // returns "PHP" console.log(languages) // returns new array without "PHP"

3. Array.prototype.pop()

` pop ()`方法与 ` shift()`方法的作用相反。它会移除数组的最后一个元素。
数组中最后一个元素的索引是数组长度减一。`pop ()`方法还会将数组长度减一,并返回被移除的元素。

const frameworks = [ "React.js", "Angular", "Vue.js", "Express.js", "Ember.js" ] const removedFramework = frameworks.pop() console.log(removedFramework) // returns "Ember.js" console.log(frameworks) // returns new array without "Ember.js"

4. 删除运算符

`pop()`和 ` shift()`方法都允许我们从数组中移除预设位置的元素,分别是数组的最后一个位置和第一个位置。虽然它们很实用,但我们无法自由地从其他位置删除元素。如果我们想要删除某个索引位置的元素,而这个索引位置既不是第一个也不是最后一个,该怎么办呢?

delete 运算符非常适合这种场景。与pop()shift()
不同,delete运算符会返回一个新的数组。

const items = ["eggs", "meat", "vegetables", "salad", "rice", "fish" ] delete items[3] console.log(items) console.log(items.length) console.log(items[3])

在使用 delete 方法之前必须注意一点:它不会像上面那样改变数组的长度。它会移除指定的元素,并在其位置添加 undefined

5. Array.prototype.splice()

如果删除运算符不太适合您,因为它不会更新数组长度,那么您可以使用的另一个内置数组方法是splice()方法。

`splice ()`方法是一个非常强大的内置数组方法,可以用来删除数组中任意索引处的元素。它也可以用于添加元素或替换现有元素。但我们这里只讨论如何从数组中删除元素。与每次只能删除一个元素的`pop()``shift()`方法不同,`splice()` 可以一次删除多个元素。
最后,`splice()`方法会返回一个包含已删除元素的新数组。

` splice()` 方法最多可以接受三个参数,但我们的用例只需要两个。第一个参数指定要从中开始删除的索引,第二个参数指定要从数组中删除的元素数量。

//remove single element const numbersInWords = [ "one", "two", "three", "four", "five", "dozen", "six" ] const arrayWithDeletedItems = numbersInWords.splice(5, 1) //returns ["dozen"] // remove multiple elements const mammals = ["man", "dog", "rat", "cat", "fish", "snake", "fly"] const nonMammals = mammals.splice(4, 3) // return ["fish", "snake", "fly"] console.log(numbersInWords) console.log(arrayWithDeletedItems) console.log(mammals) console.log(nonMammals)

6. Array.prototype.filter()

我们之前已经见识过splice()函数的强大之处,它能够从数组中任意索引的位置插入元素。但是,使用splice()函数只能一次删除多个元素。

const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20] const result = numList.splice(7, 5) console.log(result) console.log(numList)

如果我们想从上面的 numList 数组中删除所有单词该怎么办?由于上述数组中的单词并非按顺序排列,因此splice()方法并不适用。除非我们自己实现一个remove()方法,这样就可以在底层使用它。一个不错的选择是使用 filter()方法 ,因为我们要删除数组中所有相同的字符串实例。

filter ()方法会为数组中的每个元素调用一次提供的回调函数,并返回一个通过回调函数中实现的测试的新元素数组。

const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20] pureNumList = numList.filter(item => typeof item !== "string") // returns a list of numbers pureEvenNumber = numList.filter(item => typeof item !=="string" && item % 2 === 0) // returns a list of only even numbers. console.log(numList) console.log(pureNumList) console.log(pureEvenNumber)

注意到`filter()`方法的强大之处了吗?它允许我们从数组中删除多个元素,而无需考虑它们的索引。此外,还要注意如何在回调函数实现中组合条件来针对多个元素。

const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20] pureEvenNumber = numList.filter(item => typeof item !=="string" && item % 2 === 0) // returns a list of only even numbers. console.log(pureEvenNumber)

一部杰作

在 JavaScript 中还有其他方法可以实现这一点,实际上,到了这个地步,最终应该归结为开发者自己实现自定义函数。也许你梦想着拥有一个属于自己的remove()方法。最后,我想向你推荐John Resig ( jQuery的创建者)的杰作。

// Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20] numList.remove(13) numList.remove(6) console.log(numList) // returns a new array with only numbers.

8. 结语

以上列举了一些从数组中删除元素的方法,但这绝非全部方法。正如我所说,开发者总能想出新的方法。如果您有实现此任务的自定义辅助函数,欢迎在下方评论区分享。

文章来源:https://dev.to/lawrence_eagles/modern-methods-to-remove-items-from-arrays-in-javascript-3eed