vue前端关于forEach,map,findIndex,列表拼接的随笔
JavaScript 数组方法详解
1. forEach()
功能:遍历数组元素,执行回调函数(无返回值)
特点:
- 直接修改原数组(需在回调中操作)
- 无法中断循环(即使使用
return或break) - 适合执行副作用操作(如修改DOM、更新状态)
// 示例1:修改对象属性
const users = [{id:1, active:false}, {id:2, active:false}];
users.forEach(user => user.active = true); // 所有用户激活状态改为true
// 示例2:分组处理(满足需求的分组场景)
const numbers = [1,2,3,4,5];
const odd = [], even = [];
numbers.forEach(num => num % 2 === 0 ? even.push(num) : odd.push(num));
2. map()
功能:映射新数组(返回等长新数组)
特点:
- 不修改原数组(纯函数特性)
- 必须显式返回新元素
- 适合数据转换和格式化
// 示例1:提取关键字段
const products = [{id:101, name:"手机", price:2999}, {id:102, name:"耳机", price:399}];
const productNames = products.map(item => item.name); // ["手机","耳机"]
// 示例2:复杂数据结构转换
const formattedData = products.map(({id, name}) => ({
productId: `P-${id}`,
label: `${name}(商品)`
}));
/* 结果:
[
{productId: "P-101", label: "手机(商品)"},
{productId: "P-102", label: "耳机(商品)"}
]
*/
3. findIndex()
功能:查找首个符合条件的元素索引(未找到返回-1)
特点:
- 比
indexOf更灵活的查找 - 可处理对象等复杂类型
- 找到第一个匹配项立即停止遍历
// 示例:在对象数组中查找
const tasks = [
{id: 'T1', status: 'pending'},
{id: 'T2', status: 'done'},
{id: 'T3', status: 'pending'}
];
const firstPendingIndex = tasks.findIndex(
task => task.status === 'pending'
); // 返回 0
// 删除找到的元素(结合splice)
if (firstPendingIndex !== -1) {
tasks.splice(firstPendingIndex, 1);
}
4. 数组合并与扩展运算符
扩展运算符(...):
- 浅拷贝数组/对象
- 快速合并数组/对象
- 替代
concat()更直观
// 示例1:多来源数组合并
const defaultItems = [{id:0, name:"默认项"}];
const apiItems = [{id:1, name:"API数据"}];
const localItems = [{id:2, name:"本地缓存"}];
const combined = [...defaultItems, ...apiItems, ...localItems];
/* 结果:
[
{id:0, name:"默认项"},
{id:1, name:"API数据"},
{id:2, name:"本地缓存"}
]
*/
// 示例2:插入新元素(替代splice)
const inserted = [
...combined.slice(0,1),
{id: "new", name:"新增项"},
...combined.slice(1)
];
方法对比速查表
| 方法 | 返回值 | 修改原数组 | 循环中断 | 适用场景 |
|---|---|---|---|---|
| forEach | undefined | ❌ (可间接) | ❌ | 遍历执行操作 |
| map | 新数组 | ❌ | ❌ | 数据转换/格式化 |
| findIndex | 索引/-1 | ❌ | ✅ | 条件查找元素位置 |
| 扩展运算符 | 新数组/对象 | ❌ | - | 合并/插入/浅拷贝 |
进阶技巧
- 链式调用(合理组合方法)
// 获取所有未完成任务的ID
const pendingTaskIds = tasks
.filter(task => task.status === 'pending')
.map(task => `TASK-${task.id}`);
- 性能优化
- 大数据集避免链式调用(多次遍历)
- 使用
for...of+break替代findIndex需中断的场景
- 不可变数据实践
// 添加新项(不修改原数组)
const newList = [...list, newItem];
// 修改特定项
const updatedList = list.map(item =>
item.id === targetId ? {...item, value: newValue} : item
);
浙公网安备 33010602011771号