What is the main difference between:
var test=[5,6,7,8,9];
$.each(test, function (i, num) {
setTimeout(function(){console.log('i: '+i+' '+num)},500);
});
for (var j = 0; j < test.length; j++) {
setTimeout(function(){console.log('j: '+j+' '+test[j])},500);
}
First loop outputs:
i: 0 5
i: 1 6
i: 2 7
i: 3 8
i: 4 9
Second loop outputs:
5 times 'j: 5 undefined'
I understand why the second loop does this, but not why $.each works 'as expected'
Thanks!