Josh Stevenson
Josh Stevenson

Reputation: 905

Anonymous function arguments and the order they are passed

Explanation:

Something I have not been able to get my head around with anonymous functions is their arguments.

Say we are using jQuery.each();

I know that if we call each() and use what I would call an anonymous callback function
i.e.

$.each('p', function(index, item){

I can 'grab' the index and the element using an anonymous function, as seen above. Using this I could then do something like

var array = [];

$.each('p', function(index, item){
    if(index % 3 === 0) array.push(item);
});

Using the anonymous function I grabbed the index of the current element it was running the each against and then push-ed it into an array if I could divide the index by three, or basically every 3 items.

Question:

Do all methods throw different parameters for us to 'catch' with anonymous functions, or do they all follow a strict pattern of (index, element, etc.)

If they are all different, is there a way to find out what data is being passed from a method?

Upvotes: 1

Views: 76

Answers (1)

Tomas Aschan
Tomas Aschan

Reputation: 60664

No, you can't count on the arguments always being the same, as what makes sense depends a lot on context.

There is a very easy way to find out what arguments will be given: read the documentation :)

For example, the documentation for .each() reads

.each( function ) Returns: jQuery
Description: Iterate over a jQuery object, executing a function for each matched element.

function
Type: Function( Integer index, Element element )
A function to execute for each matched element.

Upvotes: 2

Related Questions