zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    安装完QQ必须要删除掉的几个恐怖文件
    dede实战系统:更换成kindEditor编辑器
    PHP 5.4 中经 htmlspecialchars 转义后的中文字符串为空的问题
    DEDECMS图片集上传图片出错302的解决办法
    dedecms安装完成后登录后台出现空白
    OFV.msi是什么 为什么更新时无法安装
    CentOS 挂载NTFS分区的两种方法
    centos使用yum安装gcc
    NetBeans菜单栏字体太小了
    注入漏洞页
  • 原文地址:https://www.cnblogs.com/shewill/p/12594337.html
Copyright © 2011-2022 走看看