• 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] 
    })
     
  • 相关阅读:
    Linux 下IOport编程訪问
    Xcode下执行HelloWorld
    PHP/HTML混写的四种方式总结
    php取两位小数的几种方法
    使用原生JS+CSS或HTML5实现简单的进度条和滑动条效果(精问)
    js进阶 9-7 自动计算商品价值
    html5--1.12表格详解
    html5常用标签table表格布局
    html常用属性border-radius、linear-gradient怎么使用
    类选择器选择非唯一属性无法精确取值的问题
  • 原文地址:https://www.cnblogs.com/yangxiaoying/p/7262135.html
Copyright © 2020-2023  润新知