核心規則一覽
| 行為 | jQuery each 寫法 | 原生循環對應 |
| 跳出循環 (break) | return false; | break; |
| 跳過本次 (continue) | return true; | continue; |
| 直接 return | 同 return false(跳出) | - |
實戰示例
場景 1:查找匹配項並停止
// 設置下拉選單選中項,找到即停止
$("#area option").each(function() {
if ($(this).text() === addrTmp[2]) {
$(this).prop("selected", true);
return false; // break - 找到即退出,提升性能
}
});
場景 2:驗證表單,遇空即停
var valid = true;
$(".required").each(function() {
if (!$.trim(this.value)) {
alert("請填寫 " + this.name);
$(this).focus();
valid = false;
return false; // 終止後續檢查
}
});
if (!valid) return;
場景 3:跳過特定項繼續處理
var items = [];
$("li").each(function(i, el) {
if ($(el).hasClass("skip")) return true; // continue
items.push({id: el.id, text: el.innerText});
});
陷阱提醒
// ❌ 錯誤:試圖在 each 回調外獲取返回值
var result = $(".item").each(function() {
if (condition) return "found"; // 這裡的返回值被 jQuery 忽略
});
console.log(result); // 返回 jQuery 對象,而非 "found"
// ✅ 正確:使用外部變量捕獲
var found = null;
$(".item").each(function() {
if (condition) {
found = this.value;
return false;
}
});
console.log(found); // 正確獲取
$.each() vs $().each() 差異
// 1. $().each() - jQuery 對象方法,遍歷 DOM 集合
$("#list li").each(function(index, element) {
// index: 0-based 索引
// element: 原生 DOM 元素
// this === element
});
// 2. $.each() - 全局工具函數,遍歷任意陣列/對象
$.each([1,2,3], function(index, value) { /* ... */ });
$.each({a:1, b:2}, function(key, value) { /* ... */ });
性能提示
- 大量數據時,
return false 早退出可顯著提速
- 純數據遍歷優先用
for/for...of/Array.prototype.forEach,避免 jQuery 封裝開銷
- ES6+ 環境下,
for (const item of items) 配合 break/continue 更直觀