zoukankan      html  css  js  c++  java
  • js/jq中遍历对象或者数组的函数(foreach,map,each)

    本文中以数组为例,对象与此方法相同。

    一、forEach遍历数组

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

      //do something

    })

    • 参数:value数组中的当前项,index当前项的索引,array原始数组;
    • 数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
    • 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组
    1 var arr=[1,2,3,4,5];
    2 var res=arr.forEach(function(value,index,array){
    3    array[index]=value*10; 
    4 })
    5 console.log(res);  //undefined
    6 console.log(arr); //[10,20,30,40,50]  //通过索引改变了原数组

    二、map函数

    arr.map(function(value,index,array){

      //do something

    })

    • 参数:value数组中的当前项,index当前项的索引,array原始数组;
    • 区别:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
    var arr=[1,2,3,4,5];
    var res=arr.map(function(value,index,array){
       return value*10; 
    });
    console.log(res);//[10,20,30,40,50],返回的新数组
    console.log(arr);  //[1,2,3,4,5] 原数组未发生改变

    三、each函数

    $.each(arr,function(index,value){

       //  do something

    })

    • 参数:arr要遍历的数组,index当前项的索引,value数组中的当前项
    • 第1个和第2个参数正好和以上两个函数是相反的,注意不要记错了
    var arr=[10,20,30,40,50];
    $.each(arr,function(index,item){
       console.log(index);//[0,1,2,3,4] 
       console.log(item);//[10,20,30,40,50] 
    })
     
  • 相关阅读:
    NOIP2014-普及组复赛-第二题-比例简化
    NOIP2014-普及组复赛-第一题-珠心算测验
    洛谷-不高兴的津津(升级版)-数组
    洛谷-陶陶摘苹果(升级版)-数组
    洛谷-小鱼比可爱-数组
    小车问题
    洛谷-小鱼的数字游戏-数组
    洛谷-校门外的树-数组
    centos 6.5 minimal 安装及vm-tools安装
    php使用第三方登录
  • 原文地址:https://www.cnblogs.com/yangxiaoying/p/7262135.html
Copyright © 2011-2022 走看看