美文网首页
map()和forEach()

map()和forEach()

作者: 李丹linda | 来源:发表于2018-10-23 09:33 被阅读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);

相关文章

  • Js数组遍历对原数组的影响及返回值

    1.map和forEach 结果:map和forEach都不改变原数组,map返回一个新数组,forEach没有返...

  • js forEach map &&&

    原生JS forEach()和map()遍历的区别以及兼容写法 一、原生JS forEach() 和map()**...

  • 36. 常用的高阶函数

    forEach 、map 利用 forEach 和 map 对数组进行操作 可以利用 map 对数组的元素进行运算...

  • map 和forEach用法(添加parseInt的小尾巴)

    forEach: map map:和forEach非常相似,都是用来遍历数组中的每一项;区别:map的回调函数中支...

  • 初探 forEach() 方法

    Map对象 Map.prototype.forEach() forEach() 方法将会以插入顺序对 Map 对象...

  • for、forEach和map比较

    for、forEach和map比较 性能比较 for循环是在有js的时候就有了,forEach和map是es5的时...

  • 【JS】map遍历数组

    这里的map不是地图的意思,而是“映射”。 map的使用方法和forEach类似。 和forEach不同的是,ma...

  • map()和forEach()

    一、相同点 1. 都是循环遍历数组中的每一项; 2. map和forEach方法里每次执行匿名函数都支持三个参数,...

  • forEach和map

    在foreach函数中使用return break,其效果等同于continue,只能终止一次循环,并不能起到跳出...

  • forEach()和map()

    自写forEach() 自写map()

网友评论

      本文标题:map()和forEach()

      本文链接:https://www.haomeiwen.com/subject/qexizftx.html