【前端_js】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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM