Why do jQuery.each () and jQuery.grep () have different parameter orders?

I noticed that there is a difference in parameter orders between the .each () and .grep () function callback in jquery.

jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] ) jQuery.each( collection, callback(indexInArray, valueOfElement) ) 

Do you have any idea of ​​the possible reasons why they preferred to have indexInArray as the 1st parameter in .each () and the 2nd in the .grep () function?

Thank burak ozdogan

+4
source share
2 answers

I don’t know if there is a real answer for this or not, but let's look at using the function:

  • In .grep , an array element is processed. The index of this item is not needed to process the item. This is more or less optional and therefore the second parameter.

  • In .each parameter is not needed. But since the element can be accessed via this inside the function, it makes sense that the element is specified as the second parameter. Thus, you do not need to specify two variables for index use only.
    If the parameters were in the reverse order and you want to use the index, you will need to specify a variable for the element, and you can no longer use this (but I'm not sure about that).

So, in the end, it's a matter of convenience.

+3
source

Well, one could say that the arguments are in the same order. If you look at the source code, you will see that in grep, the callback is called like this:

 callback( elems[ i ], i ) ) 

whereas in each (when working with an array, not with a map):

 var value = object[0]; callback.call( value, i, value ) 

where the value is the this object. This method invocation method is used to override the value of this.

Therefore, I suggest that the preferred way to use each is to use this to refer to an object.

In my opinion, this difference is not very good, as it makes the life of users more difficult. I checked and both versions were introduced in version 1.0, so it cannot be justified that this was due to two different opinions.

0
source

Source: https://habr.com/ru/post/1299302/


All Articles