$.each() / $().each() 的回調函數返回值 不會 作為整體返回值,只能控制循環流程。需用外部變量捕獲結果。
function findFirstMatch(items, predicate) {
var result = null; // 外部變量捕獲
$(items).each(function(index, item) {
if (predicate(item)) {
result = item; // 保存結果
return false; // break - 停止循環
}
});
return result; // 返回捕獲的結果
}
// 使用
var found = findFirstMatch($(".item"), function(el) {
return $(el).data("id") === 123;
});
function hasValidItem() {
var success = false; // 默認值
$(".check-item").each(function() {
var val = $(this).val();
if (val && val.length >= 5) {
success = true;
return false; // 找到即退出
}
});
return success;
}
// 調用
if (hasValidItem()) {
submitForm();
}
var data = {a: 1, b: 2, c: 3};
var foundKey = null;
$.each(data, function(key, value) {
if (value === 2) {
foundKey = key;
return false; // break
}
});
console.log(foundKey); // "b"
// ❌ 錯誤:期望 each 直接返回值
var val = $(".item").each(function() {
if (condition) return this.value; // 無效!
});
console.log(val); // 返回 jQuery 對象
// ✅ 正確:外部變量 + return false
var val = null;
$(".item").each(function() {
if (condition) {
val = this.value;
return false;
}
});
// 數組:find / findIndex / some / every
const items = [{id:1}, {id:2}, {id:3}];
const found = items.find(item => item.id === 2); // 直接返回匹配項
const has = items.some(item => item.id > 1); // 返回 boolean
// 對象:Object.keys/entries + find
const obj = {a:1, b:2};
const key = Object.keys(obj).find(k => obj[k] === 2); // "b"
return false → break(停止循環)return true → continue(跳過本次)