map + parseInt - strange results

.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.

Tags:

Javascript