• js中数组的map与forEach方法


    关于js中数组的遍历的两种方法:forEach与map

    一、forEach遍历

    1)arr.forEach(function(数组中的元素,每个元素对应得下标,数组自身){})
                arr.forEach(function(item,index,arr){
                console.log(item,index,arr);
            })
    2)forEach求数组元素之和
            var arr=[1,3,4,3,5,2,3,5,7,4,3];
            var sum=0
            arr.forEach(function(item,index,arr){
                sum+=item;
            })
            console.log(sum);//40
    3)使用forEach可以跳过空元素
            var arr=[1,3,4,3,5,,3,5,7,4,3];
            var sum=0
            arr.forEach(function(item,index,arr){
                console.log(item,index);
            })
    4)复制不带空元素的数组
            var arr=[1,3,4,3,5,,3,5,7,4,3];
            var arr1=[];
            arr.forEach(function(item,index,arr){
                arr1.push(item);
            })
            console.log(arr1);

    二、map遍历

    1)map会返回一个与原数组长度相等的新数组,arr.forEach(function(数组中的元素,每个元素对应得下标,数组自身){})
            var arr=[1,3,4,3,5,7,3,5,7,4,3];
            var arr1=arr.map(function(item,index,arr){
                // console.log(item,index,arr);
                //在map中使用return就是在对应得下标中添加对应的数据
                return item+"a";
            });
            console.log(arr1);
    2)map循环遍历,返回的数组长度与原数组一致
            var arr=[1,3,4,3,5,7,3,5,7,4,3];
            var arr1=arr.map(function(item,index,arr){
                if(item>4)
                return item
            })
            console.log(arr1);//[undefined, undefined, undefined, undefined, 5, 7, undefined, 5, 7, undefined, undefined]
    3)map也不遍历空元素

    三、forEach与map的区别

    1)forEach没有返回值,map返回一个与原数组等长的新数组
    ----------------------案例-----------------------
                var arr=[
                {id:1001,name:"电视",price:4500},
                {id:1002,name:"电脑",price:6500},
                {id:1003,name:"冰箱",price:2000},
                {id:1004,name:"洗衣机",price:1000},
                {id:1005,name:"手机",price:5500}
            ];
    //forEach方法
            arr.forEach(function(item,index,arr){
                // 给对象添加num属性,属性值随机从1到9
                item.num=parseInt(Math.random()*9+1);
                // 给对象添加total属性值
                item.total=item.price*item.num;
            })
            console.log(arr);
    //map方法
            var arr1=arr.map(function(item,index,arr){
                item.num=parseInt(Math.random()*9+1);
                item.total=item.price*item.num;
                return item;
            })
            console.log(arr1);
  • 相关阅读:
    Fody is only supported on MSBuild 16 and above
    abp发送邮件AbpMailKit
    看一位老司机的博文,分享一下。
    nginx PC 移动配置
    微信开放平台登录
    flask 中 session的源码解析
    python mac环境搭建
    前端换mac可以参考搭一下简单的环境
    vue 导航钩子
    HTML5 History 模式
  • 原文地址:https://www.cnblogs.com/shewill/p/12594337.html
Copyright © 2020-2023  润新知