简体   繁体   中英

JavaScript Puzzle: Not able to understand parseInt results in JavaScript

Can someone please explain why we are getting following results in JavaScript?

parseInt ( 'a' , 24 ) === 24 ;
>false
parseInt ( 'a' , 34 ) === 24 ;
>false
parseInt ( 'o' , 34 ) === 24 ;
>true

The second argument to parseInt is the radix.

In base 24 or 34, 'a' is equal to 10 because it is the first letter of the alphabet, so it's the first digit used after the digits 0-9. 'o' is the 15th letter of the alphabet, so it is equal to 24 in bases that have that many digits, like your last example of 34.

The second argument to parseInt(string, radix); is a integer between 2 and 36 that represents the radix of the first argument string.

The return value of parseInt(string, radix); will be the decimal integer representation of the first argument taken as a number in the specified radix.

Now,keeping that in mind if you convert them :

      Input            Output   

  a (base-24)        10 (base-10)
  a (base-34)        10 (base-10)
  o (base-34)        24 (base-10)

So, as you can see in third case it comes out to be 24 and bingo! there you go the condition is true.

You can use any online tool to convert from one number system to another like I used this one :

http://extraconversion.com/base-number/base-34

Hope this Helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM