简体   繁体   中英

Why doesn't mapping over `parseInt` point-free style work as expected?

I'm running the following in the Node.JS console:

> ["30", "31", "32"].map(x => parseInt(x))
[ 30, 31, 32 ]
> ["30", "31", "32"].map(parseInt)
[ 30, NaN, NaN ]

Why aren't these expressions identical? Is there a semantic difference in calling a function in point-free style as opposed to an anynomous function?

parseInt accepts two arguments: the numeric string and the base. Array#map provides the element and the index as the first two arguments to its callback, which makes some of the numbers unparseable (the main cause likely being that there are digits that are invalid for the specified base, such as having the digit 2 when parsing a string as binary), resulting in NaN. The Number function can be used instead to avoid this pitfall, as it ignores all arguments except the first.

["30", "31", "32"].map(Number)

 ["30", "31", "32"].map(function(){ console.log(arguments); });

The issue is most likely related to map passing more than just the element to the callback. It passes the element, index, and the whole array. So if you are letting the map pass all that into the parseInt method, the index is most likely causing issues with the method knowing how to convert the string to a number of the related base.

The function you pass to map actually gets three parameters from map : the element, the index, and the whole list.

In your first example you are explicitly binding x and passing it to parseInt , which takes two arguments, the string and a format. If you leave format null, it defaults to base 10.

In your second example, you are sending the arguments sent by map directly to parseInt , which is telling parseInt to use the index as a second argument.

> ["30", "31", "32"].map(console.log)
30 0 [ '30', '31', '32' ]
31 1 [ '30', '31', '32' ]
32 2 [ '30', '31', '32' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM