這兩個方法名字很像、用途也相關,但適用範圍完全不同,寫錯了會直接報錯。一句話區分:$.each() 是通用遍歷工具,能處理任何數組或對象;$(selector).each() 只遍歷 jQuery 對象集合。
$.each() 可以遍歷任何集合。如果是數組或含 length 屬性的偽數組對象(比如 function 的 arguments),按數字索引從 0 遍歷到 length-1;其他對象則按屬性名遍歷。回調函數的兩個參數依次是索引(或鍵名)與對應的值。
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
// 輸出
// 0: 52
// 1: 97
var map = {
'flammable': 'inflammable',
'duh': 'no duh'
};
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
// 輸出
// flammable: inflammable
// duh: no duh
回調裡 return false 可以中斷整個 $.each(),效果等同 for 循環裡的 break;返回其他任何值則等同 continue,會立刻進入下一輪:
var arr = ["one", "two", "three", "four", "five"];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("Mine is " + this + ".");
return (this != "three"); // this 為 three 時退出
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" – " + val));
});
注意遍歷數組時,回調裡的 this 會指向當前值(如 "one"、"two"),所以可以直接用 this 拼選擇器;而遍歷對象時用 i 表示鍵、val 表示值。另外 JavaScript 會把 this 包裝成對象,即使它原本是字符串或數字,必要時需注意類型判斷。
var myArray = ["skipThis", "dothis", "andThis"];
$.each(myArray, function(index, value) {
if (index == 0) {
return true; // 等同 continue,進入下一輪
}
alert(index + ": " + value);
});
遍歷 DOM 元素集合用 $(selector).each(),語義更貼切,回調裡 this 就是原生 DOM 節點;遍歷普通數組、對象或類數組則用 $.each()。兩者都返回原對象,支持鏈式調用。在現代項目中,數組遍歷可以直接用 forEach、for...of,對象遍歷用 Object.keys().forEach(),性能與可讀性通常更好。