zoukankan      html  css  js  c++  java
  • js 中 forEach 和 map

    共同点:

        1.都是循环遍历数组中的每一项。

        2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。

        3.匿名函数中的this都是指Window。

        4.只能遍历数组。

    不同点:

    1.forEach()

       没有返回值。

    arr.forEach(item =>{

      if(arr.length!=0){

      }

    })

    arr[].forEach(function(value,index,array){

      //do something

    })

    • 参数:value数组中的当前项, index当前项的索引, array原始数组;
    • 数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
    • 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;

    2.map() 

    有返回值,可以return 出来。

    this.data = [

    ]

    arr = [

      {name:'aa',sex:'man'},

      {name:'bb',sex:'feman'},

    ]

    this.data = arr.map(item =>{

      item['c'] = item['name']

      return item

    })

    • 参数:value数组中的当前项,index当前项的索引,array原始数组;
    • 区别:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
    1. var ary = [12,23,24,42,1];  
    2. var res = ary.map(function (item,index,input) {  
    3.     return item*10;  
    4. })  
    5. console.log(res);//-->[120,230,240,420,10];  原数组拷贝了一份,并进行了修改
    6. console.log(ary);//-->[12,23,24,42,1];  原数组并未发生变化
  • 相关阅读:
    linux 之 系统监控
    Spring Cloud Eureka 常用配置及说明
    mysql的事务隔离级别
    什么场景中会用到java多线程(转)
    springboot配置druid连接池
    MyBatis标签详解(转)
    关于@JsonSerialize注解的使用方法
    layer绑定回车事件(转)
    php7+apache2.4配置
    Eclipse创建Maven项目不支持el表达式的解决方式
  • 原文地址:https://www.cnblogs.com/sweet-ice/p/10591210.html
Copyright © 2011-2022 走看看