js中map和forEach的用法

本文通过实例对比了JavaScript中map与forEach方法的功能差异,包括它们如何处理简单数组及对象数组,展示了两种方法在遍历过程中的不同行为,特别是对原数组的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

编码过程中一直分不清map和forEach的区别,闲下来,弄几个例子研究一下。


一、map

1.简单数组

    const a = [ 5, 7, 10, ]
    const mapA = a.map((item, index, arr) => {
      console.log(item, index, arr)
      return item * 2
    })
    console.log(mapA)

输出:
在这里插入图片描述

2.对象数组

    const c = [
      {
        key: 'key1',
        value: 'value1',
      },
      {
        key: 'key2',
        value: 'value2',
      },
    ]
    const mapC = c.map((item, index, arr) => {
      console.log(item, index, arr)
      let res = this.$deepCopy(item)
      res.value += index
      return res
    })
    console.log(c)
    console.log(mapC)

输出:
在这里插入图片描述

所以事实上map不仅可以遍历数组,还可以返回一个新数组。

3.修改简单数组内容

    const a = [ 5, 7, 10, ]
    const mapA = a.map((item, index, arr) => {
      console.log(item, index, arr)
      arr[index] = item * 2
      return item * 2
    })
    console.log(a)
    console.log(mapA)

输出:
在这里插入图片描述

4.修改对象数组内容

    const c = [
      {
        key: 'key1',
        value: 'value1',
      },
      {
        key: 'key2',
        value: 'value2',
      },
    ]
    const mapC = c.map((item, index, arr) => {
      console.log(item, index, arr)
      let res = item
      res.value += index
      return res
    })
    console.log(c)
    console.log(mapC)

输出:

在这里插入图片描述
可见,对象数组在遍历的过程中,修改属性的值就可以影响到原数组

map的其他用法详见文档

二、forEach

1.简单数组

    const a = [ 5, 7, 10, ]
    a.forEach((item, index, arr) => {
      arr[index] = item * 2
      console.log(item, index, arr)
    })
    console.log(a)

输出:
在这里插入图片描述

2.对象数组

    const c = [
      {
        key: 'key1',
        value: 'value1',
      },
      {
        key: 'key2',
        value: 'value2',
      },
    ]
    c.forEach((item, index, arr) => {
      console.log(item, index, arr)
      item.value += index
    })
    console.log(c)

输出:
在这里插入图片描述
可见,对象数组在遍历的过程中,修改属性的值就可以影响到原数组

3.forEach() 的 continue 与 break

详见文档


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值