1. 程式人生 > >js中的forEach和jQuery中的each對比

js中的forEach和jQuery中的each對比

對於遍歷陣列的元素,js和jquery都有類似的方法,js中的是forEach方法,jquery中的則是each方法;
簡單的示例如下:

//首先定義一個數組
var arr=['a','b',12];

//當js的forEach方法的匿名函式引數列表只有一個時,代表的是陣列的元素值
arr.forEach(function(item){console.log(item); });
輸出:


12 

//當js的forEach方法的匿名函式引數列表有兩個時,前者代表的是陣列的元素值,後者代表的是索引;
arr.forEach(function(item,index){console.log(index+'-'+item); });

輸出:
0-a 
1-b 
2-12 


//jquery則不同
<ul class=list>
    <li>aaaaa</li>
    <li>bbbb</li>
    <li>cccccvvv</li>
</ul>
<script type="text/javascript">
    //當引數列表是一個時,代表的是元素的索引
    $(".list>li").each(function (item) {
        document.writeln(item);
    })
    //0 1 2

    //當引數列表是兩個時,前面的是索引,後面的是元素值:

    $(".list>li").each(function (i, item) {
        document.writeln(i + "-" + $(item).text());
    })

    //0-aaaaa 1-bbbb 2-cccccvvv
</script>