Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Design inconsistency between $.map() & .map()?

Tags:

jquery

While the interface of .map() method is .map( callback(index, domElement) ), it's $.map( array, callback(elementOfArray, indexInArray) ) for $.map()... Any idea over the reason why $.map() choose to place the returned arguments in an order such as value-index?

like image 571
gsklee Avatar asked Aug 15 '12 04:08

gsklee


2 Answers

Because the API is imperfect. It started out inconsistent, but fixing that now would break existing code that uses $.map().

  • http://bugs.jquery.com/ticket/5686: "There is no way to fix this and maintain backward-compatibility."
  • http://bugs.jquery.com/ticket/7008: "The args are reversed but it would break a lot of code to change it."
like image 180
Matt Ball Avatar answered Nov 08 '22 19:11

Matt Ball


If you study the jQuery API you will notice that all methods that work on a set of selected elements and accept callbacks, such as .each, .html, .text, etc., all pass the index of the element as first argument, i.e. .map is in line here. Usually you access the current element with this inside the callback, this is just a common pattern in jQuery and so the developers might have decided that it is more important to have the index as first argument.

On the other hand, the native Array.prototype.map method passes the value of element as first argument to the callback, so it seems to make sense that $.map works the same way, since it is supposed process a generic set of items.

like image 23
Felix Kling Avatar answered Nov 08 '22 19:11

Felix Kling