JS Array.map gotcha
Thursday, November 15th, 2012I was working on a project today and was seeing weird sort behavior and couldn’t figure out what was going on for a while. I finally discovered that JavaScript Array.map wasn’t returning the values I expected. In particular:
> "11.4.402.265".split('.').map(parseInt) [11, NaN, NaN, 2]
I was a little worried that Mozilla was broken, so I asked the JS experts in IRC and got this interesting diagnosis from Jeff Walden (Waldo):
parseInt takes a second parameter that’s a radix; map calls its function with (value, index, thisArray)
This magic behavior of Array.map can be useful if you want to do even-odd behavior or other tasks, but it happened to be my personal footgun today. Be careful! My code now interposes its own function:
a.split('.').map(function(i) { return parseInt(i); });
I’m not sure I really want to know why parseInt(11, 0) returns 11.