Monday 11 April 2016

Difference between $.each and jquery.each

Iterate over object and non-jquery objects: jquery provides an object iterator utility called $.each() and .each(). Both methods are similar only differ level of using these two methods. let understand using with information and example.

$.each();(also write like jQuery().each())
It is a generic object iterator function for looping over collection whether it's an array or array objects.

It is using instead of for and for-in.

Example:

Using for loop;

var arr = [1,2,3,4,5,6,7];
for ( var i = 0, l = arr.length; i < l; i++)
{
   console.log('index: '+i+ ' value: '+ arr[i]);
}

$.each()

var arr = [1,2,3,4,5,6,7];
$.each(arr, function(index, value)
{
console.log('index: '+index+ ' value: '+ value);
});

for in

var arr = [1,2,3,4,5,6,7];
for (var item in arr)
{
console.log('index: '+item+ ' value: '+ arr[item]);
}


Let's take an example with html elements using list.

<ul>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
</ul>

jQuery.each();

$('li a').each(function(key, value)
{
  console.log($(this).text());
});

$.each()

$.each( $('li a'), function( key, value ) 
{
 console.log(value);
});



No comments:

Post a Comment