Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map + parseInt - strange results [duplicate]

Tags:

javascript

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

prints

[1, NaN, NaN]

why?

like image 362
georg Avatar asked Dec 21 '11 18:12

georg


3 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 192
Alnitak Avatar answered Sep 23 '22 05:09

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 26
georg Avatar answered Sep 24 '22 05:09

georg


.map calls parseInt() with three parameters - the value, the array index and the whole array instance.

like image 23
user2029313 Avatar answered Sep 25 '22 05:09

user2029313