Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ["1", "2", "3"].map(parseInt) -> [ 1, NaN, NaN ] [duplicate]

Tags:

javascript

console.log("1,2,3".split(",").map(parseInt))

prints

[1, NaN, NaN]

why?

like image 364
georg Avatar asked Nov 23 '22 08:11

georg


2 Answers

.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 
like image 69
Alnitak Avatar answered Dec 15 '22 04:12

Alnitak


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))
like image 35
georg Avatar answered Dec 15 '22 03:12

georg