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] 
    })
     
  • 相关阅读:
    javaApi Swagger配置
    java跨域配置
    applation.properties与applation.yml关于sql数据库连接配置的区别
    SpringBoot学习记录一
    Centos命令行报bash:.....:command not found的解决办法
    Referenced file contains errors (http://JAVA.sun.com/xml/ns/j2ee/web-app_2_5.xsd).
    C# 两种封装的区别
    此 ObjectContext 实例已释放,不可再用于需要连接的操作。
    .net MVC ajax传递数组
    正则表达式移除首部尾部多余字符
  • 原文地址:https://www.cnblogs.com/yangxiaoying/p/7262135.html
Copyright © 2011-2022 走看看