.forEach()和.map()的区别

共同点

  1. 都只能循环 数组
  2. 都循环数组中的每一项
  3. 每次循环的 匿名函数 都有三个参数
    • 数组中的当前每一项 item
    • 当前项的索引号 index
    • 原数组 arr
  4. 匿名函数中的 this 指向 window

例如:

 let  arr = ['hi','hello','hei'];
 arr.forEach((item,index,arrays) => {
  // item为每一项 , index为每项的索引号, arrays为原数组
  console.log(item,index,arrays)
})

区别

  1. .forEach() 没有返回值,改变元数组
  2. .map(),有返回值, 返回新的数组,原数组不变

例如:
使用 forEach() 对数组进行返回

 let  arr = ['hi','hello','hei'];
 let result = arr.forEach((item,index,arrays) => {
	// item为每一项 , index为每项的索引号, arrays为原数组
    console.log(item,index,arrays)
    return  'hello world'
 })
    console.log(result)

返回结果如下:
在这里插入图片描述
使用 .map() 对数组进行返回

 let  arr = ['hi','hello','hei'];
 let result = arr.map((item,index,arrays) => {
	// item为每一项 , index为每项的索引号, arrays为原数组
    console.log(item,index,arrays)
    return  'hello world'
 })
    console.log(result)

返回结果如下:
在这里插入图片描述

用途

  1. .forEach() 不改变数据,只是用数据做一些事情
  2. .map(),需要返回一个新数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值