forEach和map

387 阅读3分钟

相同点

  1. 都是循环遍历数组中的每一项(按照原始数组元素顺序);
  2. forEach和map方法里每次执行匿名函数都支持3个参数,参数分别是item(当前每一项,必填)、index(索引值,可选)、arr(原数组,可选),this();
  3. 匿名函数中的this都是指向window;
  4. 只能遍历数组; 5.前提是回调函数不能是箭头函数,因为箭头函数没有this(否则返回undefined);
Arr.forEach((item,index,arr) => {},this)

this可选。传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值

例子:
let arr = [1,2,3,4,5];
let arr1 = [9,8,7,6,5];
arr.forEach(function(item, index, arr){ 
    console.log(this[index]);
    // 9 8 7 6 5 
}, arr1)
Arr.map((item,index,arr) => {return},thisValue)


thisValue:可选。用来绑定参数函数内部的this变量,用作 "this" 的值。
如果省略了 thisValue,或者传入 nullundefined,那么回调函数的 this 为全局对象。

例子:
let arr = ['a', 'b', 'c'];
[1, 2].map(function (e) { 
      return this[e]; 
}, arr) 
// 输出结果: ['b', 'c']

thisValue:可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。

不同点

1.forEach

没有返回值(无法赋值给新变量)

注意:

1.操作数组中元素是基本数据类型,forEach()不会改变原数组;

2.操作数组中元素是对象,forEach()会改变原数;

3.想要操作里面的基本数据类型,就用arr[i]的形式直接操作数组

2.map

有返回值return (可以赋值给新变量)

map() 不会对空数组进行检测

注意:

1.当数组中元素是值类型,map()不会改变原数组;

2.当数组中元素是引用类型,map()则可以改变原数组

代码实践

1. forEach

(1).引用类型
let obj = {'obj1':1}
let oldArr = ['string',1,obj,true]


//增
oldArr.forEach((item)=>{
    if(typeof item == 'object'){
        item['obj2']=2
    }
})
console.log(oldArr)//[...,{obj1: 1, obj2: 2},...]


//改
oldArr.forEach((item)=>{
    if(typeof item == 'object'){
        item['obj1']="obj1"
    }
})
console.log(oldArr)//[...,{obj1: "obj1"},...]


结论:上述两种方式都改变原数组
(2).值类型
//修
let oldArr1=[1,2,3]
oldArr1.forEach((item)=>{
    item = item+1
})
console.log(oldArr1)//[1,2,3]


结论:未修改原数组

2. map

(1).引用类型
let strArr=[
    {
        name:'张三',
        age:10,
    },
    {
        name:'里斯',
        age:11,
    },
    {
        name:'王二',
        age:12,
    },
]
//增
let res = strArr.map((item)=>{
    item.dis = '喜欢音乐'
    return item
})
console.log(strArr,'1')//[{name:'张三',age:10,dis:"喜欢音乐"}...]
console.log(res,'1')//[{name:'张三',age:10,dis:"喜欢音乐"}...]

//改
let res = strArr.map((item)=>{
    item.age = item.age + 3 
    return item
})
console.log(strArr,'3')//[{name:'张三',age:13}...]
console.log(res,'3')//[{name:'张三',age:13}...]


结论:改变原数组

(2).值类型
let res = numArr.map((item) => {
    item = item*3
    return item
})
console.log(numArr)//[1, 2, 3]
console.log(res)//[3, 6, 9]


结论:未改变原数组

map方法体现的是数据不可变的思想。

该思想认为所有的数据都是不能改变的,
只能通过生成新的数据来达到修改的目的,
因此直接对数组元素或对象属性进行操作的行为都是不可取的。
正确的做法应该是声明一个新变量来存储map的结果,而不是去修改原数组。

文章参考处:

https://blog.csdn.net/ZhengKehang/article/details/81281563
https://blog.csdn.net/qq_37252401/article/details/103685043
https://www.cnblogs.com/zzz-knight/p/12694753.html