arguments)。回呼參數為 (index, value),this 指向當前值(會被包裝為物件)。(index, element),this 指向原始 DOM 元素。$.each([52, 97], function(index, value) {
console.log(index + ': ' + value); // 0: 52, 1: 97
});
var map = { 'flammable': 'inflammable', 'duh': 'no duh' };
$.each(map, function(key, value) {
console.log(key + ': ' + value);
// flammable: inflammable
// duh: no duh
});
return false 中斷,return true 繼續下一輪var arr = ['one', 'two', 'three', 'four'];
$.each(arr, function(index, value) {
if (value === 'three') return false; // 等同 break
console.log(value); // one, two
});
<div class="item">A</div>
<div class="item">B</div>
$('.item').each(function(index, element) {
// this === element (原始 DOM)
console.log(index, $(this).text());
});
$.each($('.item'), ...) 雖可行,但語意不清,請直接用 $('.item').each(...)。for / for...of 比 $.each() 快,熱點迴圈建議用原生。$.each(arr, (i, v) => { ... }) 時 this 不會指向當前值,改用參數 v 即可。$.each() 是通用工具函式,$(selector).each() 是針對 DOM 集合的實例方法。理解兩者回呼簽名與 this 指向的差異,能避免踩坑並寫出更語意化的程式碼。