Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.map + parseInt [duplicate]

var timeSplit = timeCaption.innerText.trim().split(' ');
            

will yield an Array of ["10:00", "–", "18:00"]

var startStr = timeSplit[0].split(':');

will yield an Array of ["10", "00"]

var res = startStr.map(parseInt);

will yield an Array of [10, NaN]

however

var res = startStr.map(function (x) {
   return parseInt(x);
});

works correctly and will yield the "expected" Array of [10, 0]

I expect each string to be passed to parseInt which returns the correct interger value (and doing that separately also yields the correct result, just like the working code).

What am I missing here?

like image 665
MJB Avatar asked Sep 11 '25 07:09

MJB


1 Answers

parseInt accepts 2 arguments:

  1. string to be parsed
  2. radix

.map calls your function with 3 arguments:

  1. the value
  2. the index
  3. array

If you think about it,

parseInt("00", 1)

doesn't really make sense and it returns NaN. parseInt accepts radixes between 2 and 36.

like image 136
Derek 朕會功夫 Avatar answered Sep 13 '25 23:09

Derek 朕會功夫