cachaito
12/31/2014 - 5:21 PM

parseInt() & parseFloat()

Przykład pochodzi z: https://github.com/raganwald-deprecated/homoiconic/blob/master/2013/01/madness.md PS. takie podejście nazywa się functional-style programming.

['1', '2', '3'].map(parseFloat);
  //=> [1, 2, 3]

// HOWEVER:
['1', '2', '3'].map(parseInt);
  //=> [ 1, NaN, NaN ]
  
// EXPLANATION:
//This is due to Array.prototype.map passing 3 arguments to the callback function: the item, the index (starting with 0) and the reference to the array itself. 
//Function parseFloat also only needs first argument, but function parseInt expects two arguments: a string and a radix. If radix is 0, base 10 is assumed. 
//Thus the first pass of the map calls parseInt('1', 0) producing 1, but the second pass calls parseInt('2', 1) which is impossible, producing NaN.

//SOLUTION:
['1', '2', '3'].map(function(x){return parseInt(x,10);})