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]

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

相关推荐
_codemonster7 小时前
主流前端技术分层选型
前端
淼澄研学7 小时前
Kimi API黑产倒卖技术解析与Python合规接入指南
开发语言·网络·python
冻柠檬飞冰走茶8 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
wangchen_08 小时前
C++正则表达式
开发语言·c++·正则表达式
何以解忧,唯有..8 小时前
Python 元组(tuple)详解:使用、遍历与排序
开发语言·python
KANGBboy8 小时前
Python eval安全隐患
开发语言·python
IT爱学堂8 小时前
java版数据结构和算法+AI算法和技能学习指南
java·开发语言
淼澄研学9 小时前
Python结合大模型挖掘搜题长尾关键词实操指南
开发语言·python
SendTomo9 小时前
P2P文件传输工具对比:SendTomo vs send.wang
javascript·网络协议·webrtc·html5·p2p
FfHUCisI9 小时前
Golang - 信号量模式(Semaphore Pattern)
开发语言·后端·golang