JavaScript 程序:从数组中移除特定项

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 1:使用 For 循环

// program to remove item from an array

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()

// program to remove item from an array

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

    // if the element is in the array, remove it
    if(index > -1) {

        // remove item
        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]


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战