forEach和map的区别

2019-05-05  本文已影响0人  木子川页心

一、相同点

  1. 都是循环遍历数组中的每一项;
  2. map和forEach方法里每次执行匿名函数都支持三个参数,参数分别为item(数组中的每一项)、index(索引值)、arr(原数组);
  3. 匿名函数中的this都指向window
  4. 只能遍历数组
    二、不同点
    1.map()

返回一个新数组,新数组中的值为原数组调用函数处理之后的值;

map()不会改变原数组的值。

//map
        var arr = [0,2,4,6,8];
        var newArr = arr.map(function(item,index,arr){
            console.log(this);
            console.log(arr);
            return item/2;
        },this);
        console.log(newArr);

2.forEach()

forEach()方法用于调用数组的每个元素,将元素传给回调函数;
没有返回值。
//forEach
        var arr1 = [0,2,4,6,8];
        var newArr1 = arr1.forEach(function(item,index,arr1){
            console.log(this);
            console.log(arr1);
            arr1[index] = item/2;
        },this);
        console.log(arr1);
        console.log(newArr1);
上一篇 下一篇

猜你喜欢

热点阅读