js遍历数组删除指定元素

方法一:使用filter方法

可以使用数组的filter方法来遍历数组并删除指定元素。filter方法会返回一个新的数组,其中包含满足条件的元素。

javascript 复制代码
let arr = [1, 2, 3, 4, 5];
let target = 3;
 
arr = arr.filter((item) => item !== target);
console.log(arr); // [1, 2, 4, 5]

方法二:使用for循环和splice方法

可以使用for循环遍历数组,然后使用splice方法删除指定元素。splice方法会修改原数组。

javascript 复制代码
let arr = [1, 2, 3, 4, 5];
let target = 3;
 
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === target) {
    arr.splice(i, 1);
    i--; // 删除元素后,数组长度减1,需要更新索引
  }
}
console.log(arr); // [1, 2, 4, 5]

方法三:使用while循环和indexOf方法

可以使用while循环和indexOf方法遍历数组,并使用splice方法删除指定的元素,直到该元素不再存在于数组中。

javascript 复制代码
let arr = [1, 2, 3, 4, 5];
let target = 3;
 
while (arr.indexOf(target) !== -1) {
  arr.splice(arr.indexOf(target), 1);
}
console.log(arr); // [1, 2, 4, 5]

这些方法都可以用来遍历数组并删除指定元素,选择哪种方法取决于你的需求和喜好。

相关推荐
xiaofeichaichai4 小时前
Webpack
前端·webpack·node.js
fqbqrr5 小时前
2606C++,C++构的多态
开发语言·c++
问心无愧05135 小时前
ctf show web入门111
android·前端·笔记
唐某人丶5 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界5 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
biter down5 小时前
从 0 到 1 搭建 Python 接口自动化测试框架(博客系统实战)
开发语言·python
JS菌5 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel6 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端