console.log("1,2,3".split(",").map(parseInt))
prints
[1, NaN, NaN]
why?
.map
calls parseInt()
with three parameters - the value, the array index, and the array itself.
The index
parameter gets treated as the radix:
parseInt('1', 0, a); // OK - gives 1
parseInt('2', 1, a); // FAIL - 1 isn't a legal radix
parseInt('3', 2, a); // FAIL - 3 isn't legal in base 2
This is discussed in much detail here: http://www.wirfs-brock.com/allen/posts/166. Proposed solutions to this problem, along with the obvious
a.map(function(e) { return parseInt(e, 10)})
also include the Number constructor:
a.map(Number)
or a solution based on partial application (see http://msdn.microsoft.com/en-us/scriptjunkie/gg575560 for more):
Function.prototype.partial = function(/*args*/) {
var a = [].slice.call(arguments, 0), f = this;
return function() {
var b = [].slice.call(arguments, 0);
return f.apply(this, a.map(function(e) {
return e === undefined ? b.shift() : e;
}));
}
};
["1", "2", "08"].map(parseInt.partial(undefined, 10))
.map calls parseInt() with three parameters - the value, the array index and the whole array instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With