Created
February 10, 2011 20:01
-
-
Save DmitrySoshnikov/821223 to your computer and use it in GitHub Desktop.
Harmful mapping (extra args for parseInt)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = ["1", "2", "3"]; | |
// try to get mapped array | |
// containing numbers | |
console.log(a.map(parseInt)); // but get [1, NaN, NaN] ! | |
// Explanation: | |
// per step 8.c.ii of the 15.4.4.9 | |
// Array.prototype.map | |
// see: http://es5.github.com/#x15.4.4.19 | |
// `mappedValue` of every call is taken as | |
// the result of the callback function, | |
// applied for three arguments: item, index and array. | |
// parseInt accepts an optional parameter - the radix | |
// 15.1.2.2 parseInt (string , radix) | |
// see: http://es5.github.com/#x15.1.2.2 | |
// if radix is `undefined` or `0` it's assumed as `10` | |
// I.e. | |
var res = []; | |
res[0] = parseInt("1", 0, a); // 1, since radix is 0 | |
res[1] = parseInt("2", 1, a); // NaN, 2 in radix 1? | |
res[2] = parseInt("3", 2, a); // NaN, 3 in radix 2? | |
console.log(res); // [1, NaN, NaN] | |
// see http://twitter.com/#!/awbjs/status/35759670580887552 | |
// If strings are correct numbers, then Number | |
// function can be used for the case | |
console.log(a.map(Number)); // [1, 2, 3] | |
// see http://twitter.com/#!/angusTweets/status/35774944293953537 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment