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]

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

相关推荐
岁忧34 分钟前
GoLang五种字符串拼接方式详解
开发语言·爬虫·golang
tyatyatya35 分钟前
MATLAB基础数据类型教程:数值型/字符型/逻辑型/结构体/元胞数组全解析
开发语言·matlab
遇到困难睡大觉哈哈41 分钟前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
用户47949283569151 小时前
Bun 卖身 Anthropic!尤雨溪神吐槽:OpenAI 你需要工具链吗?
前端·openai·bun
p***43481 小时前
前端在移动端中的网络请求优化
前端
心无旁骛~1 小时前
python多进程和多线程问题
开发语言·python
星云数灵1 小时前
使用Anaconda管理Python环境:安装与验证Pandas、NumPy、Matplotlib
开发语言·python·数据分析·pandas·教程·环境配置·anaconda
g***B7381 小时前
前端在移动端中的Ionic
前端
kaikaile19951 小时前
基于遗传算法的车辆路径问题(VRP)解决方案MATLAB实现
开发语言·人工智能·matlab
四问四不知2 小时前
Rust语言进阶(结构体)
开发语言·后端·rust