当前位置:网站首页>js 数组移除指定元素【函数封装】(含对象数组移除指定元素)
js 数组移除指定元素【函数封装】(含对象数组移除指定元素)
2022-08-06 13:56:00 【朝阳39】
普通数组移除指定元素
// 普通数组移除指定元素
function removeItem(arr, item) {
let targetIndex = arr.findIndex((itemTemp) => itemTemp === item);
if (targetIndex !== -1) {
arr.splice(targetIndex, 1);
}
}
测试
let list = [3, 5, 2, 1, 6];
// 删除数组中的 2
removeItem(list, 2);
// list变为 [3, 5, 1, 6]
console.log(list);
对象数组移除指定元素
// 对象数组移除指定对象
function removeObjItem(arr, prop, value) {
let targetIndex = arr.findIndex((itemTemp) => itemTemp[prop] === value);
if (targetIndex !== -1) {
arr.splice(targetIndex, 1);
}
}
测试
let objList = [
{
age: 10,
},
{
age: 20,
},
{
age: 30,
},
];
removeObjItem(objList, "age", 20);
// 得到 [ { age: 10 }, { age: 30 } ]
console.log(objList);
移除数组的第一个元素
arr 为数组的变量名称
arr.shift() // 返回被删除的元素
移除数组的最后一个元素
arr 为数组的变量名称
arr.pop() // 返回被删除的元素
移除数组指定下标的元素
arr 为数组的变量名称
arr.splice(index,1)
删除数组指定下标的元素
数组长度不变,只是目标下标对应的元素变为 undefined
delete arr[index]
- arr 为数组的变量名称
- index 为目标下标
边栏推荐
- 力扣练习——46 求根到叶子节点数字之和
- Talking about Tree Arrays
- 力扣练习——55 搜索二维矩阵 II
- Golang 编码规范
- select、poll和epoll的优势和缺陷
- 剖析SGI STL内存池总结
- gcc安装问题总结
- [Blue Bridge Cup Training 100 Questions] Scratch ticket change, Blue Bridge Cup scratch competition special prediction programming questions, training simulation practice questions No. 23
- TcpServer::start都做了些什么
- ”元宇宙“必须具备这些特点
猜你喜欢

TcpServer::start都做了些什么

Analysis of Rocket MQ Crash-Safe Mechanism
![报错:C:\cb\pytorch_1000000000000\work\aten\src\ATen\native\cuda\Indexing.cu:699: block: [9,0,0],](/img/72/89ba3c4b665a953a32641a851845b3.png)
报错:C:\cb\pytorch_1000000000000\work\aten\src\ATen\native\cuda\Indexing.cu:699: block: [9,0,0],

Installation configuration of QT under Win10 (available for personal testing)

40度高温,如何通过SOLIDWORKS找到室内最凉快的地方?

Interface test CURL replication and postman's Code function

Logstash、Filebeat安装与数据同步

MODBUS转PROFINET网关将电力智能监控仪表接入PROFINET网络案例

解决spacedesk卸载/重装软件时显示 指定的账户已存在

Machine learning notes (Wu En up to the teacher)
随机推荐
如何用 Redis 实现分布式锁
==和equals()的区别
MODBUS to PROFINET gateway to connect power intelligent monitoring instrument to PROFINET network case
Buckle Exercise - 51 Searching a 2D Matrix
RPC 基础系列
The most complete technical guide for 3D format conversion tool HOOPS Exchange (1): 4 major functional characteristics and typical usage scenarios
Apple开发如何在设备中切换IAP(内购)沙盒测试账户?
具体的多路分发器:EPollPoller
运筹说 第71期|论文速读之时间背包问题
TensorRT详细入门指南
【 TypeScript will learn will be 】 you must know all about TypeScript
智慧城市系列-1
MySQL存储引擎
winbox管理端口多少?
3 d format conversion tool HOOPS Exchange using guide, beginners will look
DC-9--vulnhub靶场
剖析SGI STL空间配置器(deallocate内存回收函数和reallocate内存扩充函数)
redis data types and common commands
redis使用
池塘cPond分享会第5期 • 守望者联盟 • 巴比特副总裁马千里 • 数字艺术对Web3的价值...