4
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?

2
  • Just a heads up, if your wanting to shorten this to avoid the function / return syntax and are able to use es6 features. you can just do -> var res = startStr.map(x=>parseInt(x)); as such not a million miles of what you did. Commented Sep 15, 2017 at 22:52
  • yeah I know, im hacking together a plugin where I didn't set up es2015 transpilers, just totally "forgot" how map works -_- thx though Commented Sep 15, 2017 at 23:38

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

yeah you are right, thx
Unbelievable that I couldn't find out that by myself before reading this answer X-(
Useful note: When parseInt is given a radix of 0, it interprets the radix as 10 unless the string starts with 0x or 0X, in which case it interprets characters using a radix of 16 (skipping the 0x prefix of course), which is why the first number of the array often turns maps as expected, but the second number is NaN, and subsequent indices have unanticipated results.
1

The second argument to parseInt is the radix, or base (like 10, 16, etc, defaults to base 10). .map passes two arguments to the callback, the value at that index, and also the index. So you're calling parseInt(10, 0) which is trying to figure out what 10 is in base 0.

Comments

1

.map() calls the function with 3 arguments: The array element, the array index, and the array. parseInt takes 2 parameters: the string to parse, and the radix in which to parse it.

So startStr.map(parseInt) is calling:

parseInt("10", 0, startStr);
parseInt("00", 1, startStr);

Apparently parseInt() treats radix = 0 as no radix, so it defaults to base 10. But radix = 1 doesn't make any sense at all, so it returns NaN.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.