0

It is my understanding that the following two uses of each do the same thing. Is one preferred over the other? My objective it to create a table with the returned data. Thanks

$.get('getList.php',
function (data)
{
    $.each(data, function(i, value) {console.log(value);})
    $(data).each(function(){console.log(this);});
    for(var i=0; i<data.length; i++) {console.log(data[i]);}
    for (i in data) {console.log(data[i]);}
},'json');

1 Answer 1

6

Given that data will be a JS object and not a DOM element you should use:

$.each(data, ...

Because $.each() is intended as a generic iterator over any object or array.

The $(data).each(... syntax is intended to iterate over DOM elements contained in a jQuery object. If you create a jQuery object containing data and data is not an array I think you'll find that $(data).each(... will run one iteration that returns the whole object rather than one iteration per property. If data is an array it will iterate over the elements, but it's not really the intended use.

Using for (i in data) is fine if data is not an array (if it is an array you should use a standard for loop not a for..in), but since you're using jQuery anyway you might as well stick with $.each() unless there is a performance concern.

3
  • Thanks for the great answer. I marked it up, and will give it the best answer as long as it remains the best answer. Aug 19, 2012 at 4:53
  • One nice thing about $.each is that it doesn't have the old "closure in a for loop" problem that causes so much confusion. Aug 19, 2012 at 4:59
  • 2
    @muistooshort - True. But if we solved that problem StackOverflow would go out of business.
    – nnnnnn
    Aug 19, 2012 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.