在 JavaScript 中按值从数组中删除项目
本篇文章将讨论如何使用 JavaScript 中的 splice()
和 filter()
函数按值从数组中删除项目。
要按值从数组中删除项目,我们可以使用 JavaScript 中的 splice()
函数。splice()
函数使用索引从数组中添加或删除项目。要按值从给定数组中删除项目,你需要使用 indexOf()
函数获取该值的索引,然后使用 splice()
函数使用其索引从数组中删除该值。例如,让我们创建一个包含三个字符串值的数组,并使用 splice()
和 indexOf()
函数删除一个字符串值。请参考下面的代码。
var myArray = ['one', 'two', 'three'];
var myIndex = myArray.indexOf('two');
if (myIndex !== -1) {
myArray.splice(myIndex, 1);
}
console.log(myArray)
输出:
["one", "three"]
在上面的代码中,我们使用 if
语句来检查该值是否存在于数组中。如果该值存在,则其索引不会为 -1;否则,它将是-1。indexOf()
函数返回给定值的索引,如果它不存在于数组中,函数将返回 -1。如果该值存在于数组中,我们将使用 splice()
函数删除 myIndex
中存在的 1 个值。我们还可以通过在 splice()
函数中将其定义为第二个参数来从数组中删除多个值。console.log()
函数将在控制台上从数组中删除项目后显示新数组。
要按值从数组中删除项目,我们可以使用 JavaScript 中的 filter()
函数。filter()
函数用于通过对数组的每个值应用 filter()
函数内部定义的函数来过滤给定数组中的值。在我们的例子中,我们将在 filter()
函数内定义一个函数,它将返回所有值以接受我们想要从数组中删除的值,并将结果存储在一个新数组中。例如,让我们创建一个包含三个字符串值的数组,然后使用 filter()
函数,我们将创建另一个数组,该数组将包含第一个数组的所有值,但要删除的值除外。这样,我们原来的数组就不会改变了。请参考下面的代码。
var myArray = ['one', 'two', 'three'];
var newArray = myArray.filter(function(f) { return f !== 'two' })
console.log(newArray)
输出:
["one", "three"]
在上面的代码中,我们从数组中删除了值 two
并将结果保存在变量 newArray
中,该变量将显示在控制台上。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。