天天看點

forEach和$.each()以及$().each()的用法

  1. forEach:即Array.prototype.forEach,這是ES5中對數組新增的方法,等同于過去的for循環周遊數組。用法:arr.forEach(function(value,index,array){...}),其中的function中有按個參數,value為數組中的值,index為數組下标,array為數組本身。forEach會跳過數組中不存在的元素,但不會跳過null和undefined的元素。比如數組[1,undefine,null,,2],那麼隻有第四個元素不會列印出來。注意與map的差別。
  2. $.each():方法是jQuery中的執行個體方法,用法:$.each(array,function(index,value){...}),參數有兩個,第一個為傳入的數組array,第二個為函數,函數中還有兩個參數,index為數組下标,value為數組中下标對應值。
  3. $().each():一看帶有$,顧名思義也是jQuery中的方法,這是一個對象方法,由‘$()’選擇對象數組,分别對每個對象進行操作,用法$('selector').each(function(index,value){...})。

例子如下:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>forEach與each用法比較</title>
    <script src="jquery-3.2.1.js" type="text/javascript"></script>  <!-- 需要引入jq -->
</head>
<body>
<div>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
</div>
<script>
    var group = [1,3,5,7,9];
    //forEach()隻有一個參數function時:
    group.forEach(function(value,index,array){ //function()中有三個參數
        console.log(value); //對應數組中每個參數的值;輸出五次,依次為1,3,5,7,9
        console.log(index); //對應數組下标(從0開始計算);輸出五次,依次為0,1,2,3,4
        console.log(array); //數組本身,即是->group;輸出五次,每次都輸出整個grounp數組
        console.log(this);  //undefined
    });
    //forEach()有兩個參數function和thisArg(即改變this指向的參數):
    group.forEach(function(value,index,array){
        console.log(value);
        console.log(index);
        console.log(array);
        console.log(this);  //輸出同console.log(array),因為第二個參數指向了該group數組本身
    },group);

    $.each(group,function(index,value){ //$.each()是jq中的方法,function()中有兩個參數
        console.log(index); //對應數組下标(從0開始計算);輸出五次,依次為0,1,2,3,4
        console.log(value); //對應數組中每個參數的值;輸出五次,依次為1,3,5,7,9
     });

    $('li').each(function(index,value){ //$().each()對象方法
        console.log(index+": "+$(this).text());
    });

    var g_li = $('li');
    $.each(g_li,function(index,value){ //$.each()類方法,該結果與上面結果相同,即證明$.each即是jq中對象方法,又是jq的類方法
        console.log(index+": "+$(this).text());
    });

    var result = group.map(function(value,index,array){ //function()中有三個參數
        console.log(index); //對應數組下标(從0開始計算);輸出五次,依次為0,1,2,3,4,同$.each
        console.log(value); //對應數組中每個參數的值;輸出五次,依次為1,3,5,7,9,同$.each
        console.log(array); //數組本身,即是->group;輸出五次,每次都輸出整個grounp數組
        return value + 1; //支援傳回值(與forEach的不同之處,forEach不支援傳回值)
    });
    console.log('map函數傳回值'+result); //result為數組,輸出2,4,6,8,10 console.log('map finished!');
</script>
</body>
</html>
           

ES5中還新增了一些其他對數組操作的方法:

  1. map
  2. fifter
  3. some
  4. every
  5. indexOf
  6. lastindexOf
  7. reduce
  8. reduceRight

了解這些方法請檢視: http://www.zhangxinxu.com/wordpress/2013/04/es5%E6%96%B0%E5%A2%9E%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95/

繼續閱讀