May someone explain to me the 'each' method here?

$.getJSON("https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=codecademy&callback=?",
  function(response) {
    console.log(response.responseData);
    $.each(response.responseData.entries, function (i,newsItem) {
        $("#newsfeed").append("<li>"+newsItem.title+"</li>");
    });
  });

-Code taken from Codecademy

After looking at the code along my paper and pencil in hand, I've come to comprehend the following things:

However, I failed to understand (even after a lot of trial and error-- removing some pieces of code and observing changes) the role of passing two arguments (i and newsItem) to the function for $.each. What exactly do those arguments mean and from where do we get them? What is their value?

Edit: Sorry for putting up a bad question. I actually did go to the docs and I did look-up the .each function, however, after seeing the first example I came back as it clearly did not have two arguments being passed to the function.

Upvotes: 0

Views: 55

Answers (2)

Andi N. Dirgantara
Andi N. Dirgantara

Reputation: 2051

You can look at this jQuery $.each documentation http://api.jquery.com/jquery.each/. 1st param is index, 2nd is the element.

Upvotes: 1

Lix
Lix

Reputation: 47986

These arguments is what the callback function for the $.each method requires.

The first argument (i) is the current index that the function is iterating on. First element will have the value of 0 for i, the second will have 1, etc... If you are iterating over an object, this value will be the current key of the item.

The second parameter is the actual element for the current iteration.

A simple example:

$.each( [ "a", "b", "c" ], function( index, elem ){
  console.log( index, elem );
});

This will yield the following output:

0, "a"
1, "b"
2, "c"

Upvotes: 1

Related Questions