JavaScript 从数组中删除索引
本教程讲授如何从 JavaScript 中的数组中删除特定元素。
splice()
方法可以通过添加/删除元素来修改数组的内容。它采用以下 3 个参数:
const array = [1, 2, 3, 4, 5];
const index = array.indexOf(3);
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
输出:
[1, 2, 4, 5]
在上面的代码中,我们首先找到要删除的元素的索引,然后使用 splice()
方法删除数组元素。
filter
方法循环遍历数组并滤除满足特定给定条件的元素。我们可以使用它删除目标元素并保留其余元素。它有助于我们同时删除多个元素。
var toRemove = 1;
var arr = [1, 2, 3, 4, 5];
arr = arr.filter(function(item) {
return item !== toRemove
});
console.log(arr)
输出:
[2, 3, 4, 5]
我们使用 filter
函数来保留每个不等于要删除的元素的元素,并将新形成的数组分配给原始数组。
Underscore.js
是一个非常有用的库,它为我们提供了许多有用的功能,而无需扩展任何内置对象。要从 JavaScript 数组中删除目标元素,我们必须使用 without()
函数。此函数返回数组的副本,其中删除了目标元素的所有副本。
const arr = [1, 2, 1, 0, 3, 1, 4];
arr = _.without(arr, 0, 1);
console.log(arr);
输出:
[2, 3, 4]
在上面的代码中,我们将数组和要删除的元素 0
和 1
传递给了 without
函数。它返回一个删除了这些元素的新数组,我们将其再次存储在 arr
中。
Lodash
是一个很棒的库,它允许我们仅导入所需的函数,而不导入完整的库。它有一个名为 remove()
的函数,可以从数组中删除一个特定的元素。该函数采用数组,并检查与要从数组中删除的元素相匹配的条件。
var arr = [1, 2, 3, 4];
var greater = _.remove(arr, function(n) { return n > 2;});
console.log(arr)
输出:
[1,2]
在上面的代码中,我们将数组和一个函数检查元素是否大于 2
传递给 lodash
库的 remove
函数。它从数组中删除所有大于 2
的元素。
相关文章
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 事件。