前端map函数用法

map 是数组的高阶函数,它不会修改原始数组,而是返回一个新数组,其中包含了对原始数组每个元素执行操作后的结果。

基本语法

const newArray = array.map((element, index, array) => {
  // 进行操作
  return newElement;
});

 示例

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // 输出: [2, 4, 6, 8]

使用索引 

const numbers = [10, 20, 30];
const indexed = numbers.map((num, index) => `${index}: ${num}`);
console.log(indexed); // 输出: ["0: 10", "1: 20", "2: 30"]

处理对象数组

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];
const usernames = users.map(user => user.name);
console.log(usernames); // 输出: ["Alice", "Bob", "Charlie"]

与其他函数结合使用 如filter、map

const numbers = [1, 2, 3, 4, 5];
const result = numbers
  .filter(num => num % 2 === 0)  // 先筛选出偶数
  .map(num => num * 10);          // 然后将偶数乘以 10
console.log(result); // 输出: [20, 40]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值