$.each() 是一個通用的遍歷函數,可用來遍歷物件與陣列。對於陣列,以及含有 length 屬性的偽陣列物件(例如 function 的 arguments 物件),它以數字索引從 0 到 length-1 進行遍歷;而對於其他物件,則透過屬性進行遍歷。
$.each() 與 $(selector).each() 最大的不同在於:後者專門用於遍歷 jQuery 物件,前者則可以遍歷任何集合(無論是陣列或物件)。如果是陣列,回調函數每次會傳入索引與對應的值(值也可以透過 this 關鍵字取得,但 JavaScript 會把 this 包裝成一個物件——即便它本是字串或數字),方法會回傳被遍歷物件的第一個參數。
程式碼如下:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
</script>
</body>
</html>
//輸出
0: 52
1: 97
程式碼如下:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
var map = {
'flammable': 'inflammable',
'duh': 'no duh'
};
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
</script>
</body>
</html>
//輸出
flammable: inflammable
duh: no duh
回調函數中 return false 時可以退出 $.each();若回傳非 false 值,則如同 for 迴圈中的 continue,會立即進入下一輪遍歷。
程式碼如下:
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
div#five { color:red; }
</style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<script>
var arr = [ "one", "two", "three", "four", "five" ];//數組
var obj = { one:1, two:2, three:3, four:4, five:5 }; // 對象
jQuery.each(arr, function() { // this 指定值
$("#" + this).text("Mine is " + this + "."); // this指向為數組的值, 如one, two
return (this != "three"); // 如果this = three 則退出遍歷
});
jQuery.each(obj, function(i, val) { // i 指向鍵, val指定值
$("#" + i).append(document.createTextNode(" – " + val));
});
</script>
</body>
</html>
// 輸出
Mine is one. – 1
Mine is two. – 2
Mine is three. – 3
- 4
- 5
程式碼如下:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
$.each( ['a','b','c'], function(i, l){
alert( "Index #" + i + ": " + l );
});
</script>
</body>
</html>
程式碼如下:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
$.each( { name: "John", lang: "JS" }, function(k, v){
alert( "Key: " + k + ", Value: " + v );
});
</script>
</body>
</html>
如果不想輸出第一項,可以使用 return true 進入下一輪遍歷:
程式碼如下:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
var myArray=["skipThis", "dothis", "andThis"];
$.each(myArray, function(index, value) {
if (index == 0) {
return true; // equivalent to 'continue' with a normal for loop
}
// else do stuff…
alert (index + ": "+ value);
});
</script>
</body>
</html>
透過以上範例不難看出,$.each() 的靈活性遠勝於 $(selector).each(),無論是陣列、物件還是偽陣列,都能輕鬆應對,是日常開發中相當實用的工具方法。