返回
JavaScript数组九:map()方法使用指南
前端
2023-10-24 16:44:41
map()方法介绍
作用
map()方法的作用是对数组中的每一项进行加工,返回一个加工后的新数组。它不会改变原数组。
语法
arr.map((item, index, array) => {
// 对item进行加工
});
参数
参数 | 说明 |
---|---|
item | 当前项 |
index | 当前项索引 |
array | 当前数组 |
返回值
map()方法返回一个新的数组,该数组的每一项都是对原数组中相应项进行加工后的结果。
实现原理
map()方法的实现原理是:
- 创建一个新数组。
- 遍历原数组的每一项。
- 对每一项调用回调函数,并将结果添加到新数组中。
- 返回新数组。
map()方法使用场景
map()方法可以用于各种场景,包括:
- 将数组中的每一项转换为另一种类型。
- 从数组中筛选出满足特定条件的项。
- 对数组中的每一项执行某种操作。
- 将数组中的每一项与另一个数组中的相应项合并。
map()方法示例
将数组中的每一项转换为另一种类型
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
从数组中筛选出满足特定条件的项
const fruits = ['apple', 'banana', 'cherry', 'durian', 'elderberry'];
const sweetFruits = fruits.filter(fruit => fruit.includes('berry'));
console.log(sweetFruits); // ['cherry', 'elderberry']
对数组中的每一项执行某种操作
const tasks = [{
id: 1,
name: 'task 1',
status: 'new'
}, {
id: 2,
name: 'task 2',
status: 'in progress'
}, {
id: 3,
name: 'task 3',
status: 'completed'
}];
const updatedTasks = tasks.map(task => {
if (task.status === 'new') {
task.status = 'in progress';
} else if (task.status === 'in progress') {
task.status = 'completed';
}
return task;
});
console.log(updatedTasks);
// [
// { id: 1, name: 'task 1', status: 'in progress' },
// { id: 2, name: 'task 2', status: 'completed' },
// { id: 3, name: 'task 3', status: 'completed' }
// ]
将数组中的每一项与另一个数组中的相应项合并
const users = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' }
];
const scores = [
{ id: 1, score: 90 },
{ id: 2, score: 80 },
{ id: 3, score: 70 }
];
const usersWithScores = users.map((user, index) => {
return {
id: user.id,
name: user.name,
score: scores[index].score
};
});
console.log(usersWithScores);
// [
// { id: 1, name: '张三', score: 90 },
// { id: 2, name: '李四', score: 80 },
// { id: 3, name: '王五', score: 70 }
// ]
总结
map()方法是一个非常强大的数组处理方法,可以用于各种场景。它可以帮助您轻松地将数组中的每一项转换为另一种类型、从数组中筛选出满足特定条件的项、对数组中的每一项执行某种操作、将数组中的每一项与另一个数组中的相应项合并等。
熟练掌握map()方法的使用技巧,可以帮助您在数组处理中更加高效便捷。