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] 
    })
     
  • 相关阅读:
    UVA101 The Blocks Problem 题解
    洛谷P2790 ccj与zrz之积木问题 题解
    NOIp2018 TG day1 T2暨洛谷P5020 货币系统:题解
    网页学习:day1
    NOIP2018提高/普及成绩
    NOIP2018普及T4暨洛谷P5018 对称二叉树题解
    NOIP2018&2013提高组T1暨洛谷P5019 铺设道路
    比赛:小奔的方案 solution
    比赛:小奔的矩形solution
    比赛:小奔与不等四边形solution
  • 原文地址:https://www.cnblogs.com/yangxiaoying/p/7262135.html
Copyright © 2011-2022 走看看