I was bored and lurking at GitHub Explore Timeline, this Gist caught my eye, “Hey, javascript! Are you fucking kidding me?!”
> ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09"].map(parseInt); [0, NaN, 0, 0, 0, 0, 0, 0, 0, 0] > ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09"].map(function(item) { return parseInt(item); }); [0, 1, 2, 3, 4, 5, 6, 7, 0, 0] > ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09"].map(function(item) { return parseInt(parseFloat(item)); }); [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I found it’s quite interesting to see a code fall into pitfall twice in one line of code. There is nothing wrong with map or parseInt I am afraid. JavaScript wasn’t kidding with this Gist creator.
The mapped/callback function of map receives three arguments, the element, index, and the array. As you know, you don’t have to list/supply all three when you are defining/invoking a function.
In the first line, the input arguments from map causes parseInt think you are asking different base when parsing. parseInt also accepts number base besides the string.
The second line still gets unexpected, although correct, answers. That is because 0# is generally considered as Octal number in programming languages, though not standardized in JavaScript. So, you can’t really to expect it will be read as human does.
The last one, parseFloat is not the solution, it works because it’s always base 10. In fact, using Math.floor instead of parseInt for second parsing looks little better to me, although it’s still so bad. Or just drop the second parsing, they are all type Number and they does not contain any error during the parsing. It’s unnecessary code.
One proper way to code this is
["00", "01", "02", "03", "04", "05", "06", "07", "08", "09"].map( function(item){return parseInt(item, 10);});
This is rigorous and clear but, well, long.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.