首页 > 编程语言 > 详细

js中数组的map与forEach方法

时间:2020-03-29 20:58:07      阅读:46      评论:0      收藏:0      [点我收藏+]

关于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);

 

js中数组的map与forEach方法

原文:https://www.cnblogs.com/shewill/p/12594337.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!