zoukankan      html  css  js  c++  java
  • 原生JS forEach()和map()遍历,jQuery$.each()和$.map()遍历

    一、原生JS forEach()和map()遍历

    共同点:

    1.都是循环遍历数组中的每一项。 
    2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。 
    3.匿名函数中的this都是指Window。 
    4.只能遍历数组。

    1.forEach()

    没有返回值,修改的是原数组。

    var ary = [12,23,24,42,1];  
        var res = ary.forEach(function (item,index,input) {  
               input[index] = item*10;  
        })  
        console.log(res);//-->undefined;  
        console.log(ary);//-->[ 120, 230, 240, 420, 10 ];

    2.map()

    有返回值,可以return 出来。不修改原数组。

    var ary = [12,23,24,42,1];  
    var res = ary.map(function (item,index,input) {  
        return item*10;  
    })  
    console.log(res);//-->[120,230,240,420,10];  
    console.log(ary);//-->[12,23,24,42,1]; 

    二、jQuery .each().map()遍历

    共同点:

    即可遍历数组,又可遍历对象。

    1.$.each()

    没有返回值。$.each()里面的匿名函数支持2个参数:当前项的索引i,数组中的当前项n。如果遍历的是对象,k 是键,n 是值。

    $.each( ["a","b","c"], function(i, n){  
      console.log( i + ": " + n );  
    }); 
      // 0: a
      // 1: b
      // 2: c
    
     $.each( { name: "John", lang: "JS" }, function(k, n){  
            console.log( "Name: " + k + ", Value: " + n );  
        });  
         //Name: name, Value: John 
        // Name: lang, Value: JS

    2.$.map()

    有返回值,可以return 出来。.map()2.each()里的参数位置相反:数组中的当前项n,当前项的索引i。如果遍历的是对象,i 是值,n 是键。如果是("span").map().each() ,$(“span”).each()一样。

    var arr=$.map( [0,1,2], function(n,i){  
             return n+i;
        });  
        console.log(arr); 
        //[ 0, 2, 4 ]
    
    $.map({"name":"Jim","age":17},function(n,i){  
         console.log(n+":"+i);  
     }); 
        //Jim:name
        //17:age


  • 相关阅读:
    hdu 1402 大数A*B模板(FFT)
    ccpc 哈尔滨L题 LRU Algorithm
    今年得慢慢学的
    Codeforces Round #629 (Div. 3) E. Tree Queries(LCA)
    Codeforces Global Round 7 D2. Prefix-Suffix Palindrome (Hard version) -- manacher
    hdu 3068 (manacher算法)
    用Socket API建立简易tcp服务端和客户端
    Win下建立Socket时注意事项
    线段树(Segment Tree)
    Codeforces Round #643 (Div. 2)
  • 原文地址:https://www.cnblogs.com/chiangyibo/p/8278642.html
Copyright © 2011-2022 走看看