1. 程式人生 > 實用技巧 >array.forEach和$.each()及$().each()的用法與區別

array.forEach和$.each()及$().each()的用法與區別

1.$.each():方法是jQuery中的方法,用於遍歷陣列或物件。用法:$.each(array,function(index,value){...}),有兩個引數,第一個為待遍歷的陣列或物件,第二個為回撥函式,函式中的兩個引數,index為當前遍歷到的元素下標或物件的key,value為當前遍歷到的陣列元素或物件的值。
2.$().each():一看帶有$,顧名思義也是jQuery中的方法,多用於遍歷dom陣列。用法$('selector').each(function(index,value){...})。

3.forEach:即Array.prototype.forEach,只有陣列才有的方法,等同於過去的for迴圈遍歷陣列。用法:arr.forEach(function(item,index,array){...}),其中回撥函式有3個引數,item為當前遍歷到的元素,index為當前遍歷到的元素下標,array為陣列本身。forEach方法不會跳過null和undefined元素。比如陣列[1,undefine,null,,2]中的四個元素都將被遍歷到,注意與map的區別。

【1】$('selector').each(function(index,value){...})

$("input[name='ch']").each(function(index,value){
    if($(this).attr("checked")==true){
        //一些操作程式碼
    }
}

【2】$.each(array,function(index,value){})

遍歷物件
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
console.log(key+":"+val);
});
遍歷陣列
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});

【3】arr.forEach(function(item,index,array){...})

var arr=[1,2,3,4];
arr.forEach(function(val,index,arr){
    arr[index]=2*val;
});
console.log(arr);//結果是修改了原陣列,為每個數乘以2