1. 程式人生 > >jquery中$.each的用法

jquery中$.each的用法

不用 for循環 class 自己 obj this 循環 用法 索引

對於遍歷一個數組,用$.each()來處理,簡直爽到了極點。例如:

$.each([{“name”:”limeng”,”email”:”xfjylimeng”},{“name”:”hehe”,”email”:”xfjylimeng”},function(i,n)
{
alert(“索引:”+i,”對應值為:”+n.name);
});

參數i為遍歷索引值,n為當前的遍歷對象.

var arr1 = [ “one”, “two”, “three”, “four”, “five” ];
$.each(arr1, function(){
alert(this);
});
輸出:one two three four five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
輸出:1 4 7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
輸出:1 2 3 4 5

在jQuery裏有一個each方法,用起來非常的爽,不用再像原來那樣寫for循環,jQuery源碼裏自己也有很多用到each方法。

jquery中$.each的用法