The title

This problem as a JS classic problem, should a lot of people have seen, today, WE will re-analyze and extend.

First of all, map should be familiar to you, mainly parseInt. ParseInt is a function that converts a string to an integer. The answer is [1,2,3]. Well, now that I ask, it’s not.

The correct answer is: [1,NaN,NaN]. But why?

Analysis of the

The reason for this is that map normally only takes the first parameter it passes into the callback, but it actually has two other parameters: index and array. As it happens, parseInt can take two arguments: string and radix.

As a result, finally the result returned is [parseInt (‘ 1 ‘, 0), parseInt (‘ 2 ‘, 1), parseInt (‘ 3 ‘, 2)]

At this point, however, some students are still not sure why the answer is [1,NaN,NaN]. If so, you might want to consolidate your JS base.

extended

According to MDN:

Radix optional

  • The number from 2 to 36 represents the cardinality of the string. For example, if 16 is specified, the parsed value is a hexadecimal number. Note that 10 is not the default!

If the radix is undefined, 0, or unspecified, JavaScript assumes the following:

  • If the inputstring"0x"or"0X"(a 0 followed by a lowercase or uppercase X), thenradixAssumed to be 16, the rest of the string is parsed as a hexadecimal number.
  • If the inputstringIn order to"0"At the beginning,radixIs assumed to be 8 (octal) or10(Decimal). Which one to chooseradixDepends on the implementation. ECMAScript 5 clarifies what should be used10(decimal), but not all browsers support it. Therefore, in useparseIntBe sure to specify oneradix.
  • If the inputstringStarting with any other value,radix10(Decimal).

In this particular scenario, it’s

  • parseInt(‘1’,0)The equivalent of1In decimal notation, of course1.
  • parseInt(‘2’,1)Because 1 is not thereradixThe selection range of any willradixIf an integer other than 2-36 is specified, the return value isNaN. If the radix is not an integer, the radix defaults to 10 (under Chrome).
  • parseInt(‘3’,2)So does the return value of this expressionNaNBut for quite different reasons. I’m going to return hereNaNBecause 3 is not a binary expression character and therefore cannot be converted, it is returnedNaN.

If you see this for the first time, is there a JS is really exquisite ah feeling?

extension

This question should be a more classic question, but we have not thought, if he carried out an extension, you also answer it?

[“0x10″,”2″,”123”].map(parseInt)

If you are interested, please share the answer and why in the comments section.