示例 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]

