zoukankan      html  css  js  c++  java
  • 数组中的forEach和map的区别

    大多数情况下,我们都要对数组进行遍历,然后经常用到的两个方法就是forEach和map方法。
    先来说说它们的共同点

    相同点

    • 都是循环遍历数组中的每一项
    • forEach和map方法里每次执行匿名函数都支持3个参数,参数分别是item(当前每一项),index(索引值),arr(原数组)
    • 匿名函数中的this都是指向window
    • 只能遍历数组
    • 都不会改变原数组

    区别

    map方法
    1.map方法返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。
    2.map方法不会对空数组进行检测,map方法不会改变原始数组。
    3.浏览器支持:chrome、Safari1.5+、opera都支持,IE9+,

    array.map(function(item,index,arr){},thisValue)
    
    var arr = [0,2,4,6,8];
    var str = arr.map(function(item,index,arr){
        console.log(this); //window
        console.log("原数组arr:",arr); //注意这里执行5次
        return item/2;
    },this);
    console.log(str);//[0,1,2,3,4]
    

    若arr为空数组,则map方法返回的也是一个空数组。
    forEach方法
    1.forEach方法用来调用数组的每个元素,将元素传给回调函数
    2.forEach对于空数组是不会调用回调函数的。

    Array.forEach(function(item,index,arr){},this)
    var arr = [0,2,4,6,8];
    var sum = 0;
    var str = arr.forEach(function(item,index,arr){
        sum += item;
        console.log("sum的值为:",sum); //0 2 6 12 20
        console.log(this); //window
    },this)
    console.log(sum);//20
    console.log(str); //undefined
    

    无论arr是不是空数组,forEach返回的都是undefined。这个方法只是将数组中的每一项作为callback的参数执行一次。

  • 相关阅读:
    git线上操作
    IDEA快捷方式
    Java 四种线程池
    java 获取当前天之后或之前7天日期
    如何理解AWS 网络,如何创建一个多层安全网络架构
    申请 Let's Encrypt 通配符 HTTPS 证书
    GCE 部署 ELK 7.1可视化分析 nginx
    使用 bash 脚本把 AWS EC2 数据备份到 S3
    使用 bash 脚本把 GCE 的数据备份到 GCS
    nginx 配置 https 并强制跳转(lnmp一键安装包)
  • 原文地址:https://www.cnblogs.com/sminocence/p/8385083.html
Copyright © 2011-2022 走看看