跳到主要内容

JavaScript 从数组中移除特定元素的程序

要理解这个示例,你应该了解以下JavaScript编程主题的知识:

示例1:使用For循环

// 程序:从数组中移除项

function removeItemFromArray(array, n) {
const newArray = [];

for (let i = 0; i < array.length; i++) {
if (array[i] !== n) {
newArray.push(array[i]);
}
}
return newArray;
}

const result = removeItemFromArray([1, 2, 3, 4, 5], 2);

console.log(result);

输出

[1, 3, 4, 5]

在上述程序中,使用for循环从数组中移除了一个项。

这里,

  • 使用for循环遍历数组的所有元素。
  • 在遍历数组元素时,如果要移除的项不匹配数组元素,那么该元素被推送到newArray中。
  • push()方法将元素添加到newArray中。

示例2:使用Array.splice()

// 程序:从数组中移除项

function removeItemFromArray(array, n) {
const index = array.indexOf(n);

// 如果元素在数组中,移除它
if (index > -1) {
// 移除项
array.splice(index, 1);
}
return array;
}

const result = removeItemFromArray([1, 2, 3, 4, 5], 2);

console.log(result);

输出

[1, 3, 4, 5]

在上述程序中,一个数组和要移除的元素被传递到自定义的removeItemFromArray()函数。

这里,

const index = array.indexOf(2);
console.log(index); // 1
  • indexOf()方法返回给定元素的索引。
  • 如果元素不在数组中,indexOf()返回**-1**。
  • if条件检查是否要从数组中移除的元素存在。
  • splice()方法用于从数组中移除元素。

注意:上述程序仅适用于没有重复元素的数组。

数组中仅移除了匹配的第一个元素。

例如,

[1, 2, 3, 2, 5]的结果是[1, 3, 2, 5]