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');
Given that
datawill be a JS object and not a DOM element you should use: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 containingdataanddatais 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. Ifdatais an array it will iterate over the elements, but it’s not really the intended use.Using
for (i in data)is fine ifdatais not an array (if it is an array you should use a standardforloop not afor..in), but since you’re using jQuery anyway you might as well stick with$.each()unless there is a performance concern.