I am using the following scripts to iterate the object (I don't know which one is best to use, please tell me which one is the best):
var days = {Sunday: 0, Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6};
$.each(days, function(key, value){
$('#days').append('<li>' + key + '(' + value + ')</li>');
});
for(var key in days){
$('#days').append('<li>' + key + '(' + days[key] + ')</li>');
}
The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.
Just as a loop is an embodiment of a piece of code we wish to have repeated, a function is an embodiment of a piece of code that we can run anytime just by calling it into action. A given loop construct, for instance could only be run once in its present location in the source code.
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
Looping through collections If you'd like to loop through multiple elements in a collection, you can use a normal for loop or jQuery's each() : $("p"). each(function(index, element) { $(element). text( $(element).
Either way, you should be caching that selector:
var elem = $( '#days' );
$.each(days,function(key,value){
elem.append('<li>'+key+'('+value+')</li>');
});
.each() would be better in this case. The pattern is cleaner.
With a for loop, you'd want to use obj.hasOwnProperty(key) so that you don't dredge through inherited properties... Which adds another layer of indenting:
var elem = $( '#days' );
for( var key in days ){
if( days.hasOwnProperty( key ) ){
elem.append('<li>'+key+'('+days[key]+')</li>');
}
}
It is clear without any performance tests that native javascript for loop is faster, but there is no big difference for small arrays like 10-20 small items. So use whichever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With