示例 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]
另请阅读