Monday, September 28, 2015

JavaScript arrays and iterating jQuery array-like objects

It took me a few moments to figure out.

jQuery map: http://api.jquery.com/map/



JavaScript map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map



Notice the difference: both map functions accept callback, but the order of 'index' and actual thingy (array element or DOM element) differs.

To circumvent that I'm calling $.makeArray method: https://api.jquery.com/jQuery.makeArray/

See live example here: http://plnkr.co/edit/toSy8o4kFSiStnLWpJa2?p=preview

Would be nice if it was consistent - index always first... I wonder what were design considerations back then...

How I discovered this 'issue'? (it's not an issue, it's me now knowing exactly what are library function I'm using) I use jQuery selector to fetch some data embedded in the DOM and for testing purposes I just created a hardcoded array and things started to break.

#PEACE