Why is it that parseInt(8,3) == NaN and parseInt(16,3) == 1?

后端 未结 3 1322
别跟我提以往
别跟我提以往 2020-12-07 08:39

I\'m reading this but I\'m confused by what is written in the parseInt with a radix argument chapter

Why is it that parseInt(8, 3)

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 09:19

    /***** Radix 3: Allowed numbers are [0,1,2] ********/
    parseInt(4, 3); // NaN - We can't represent 4 using radix 3 [allowed - 0,1,2]
    
    parseInt(3, 3); // NaN - We can't represent 3 using radix 3 [allowed - 0,1,2]
    
    parseInt(2, 3); // 2   - yes we can !
    
    parseInt(8, 3); // NaN - We can't represent 8 using radix 3 [allowed - 0,1,2]
    
    parseInt(16, 3); // 1  
    //'16' => '1' (6 ignored because it not in [0,1,2])    
    
    /***** Radix 16: Allowed numbers/characters are [0-9,A-F] *****/ 
    parseInt('FOX9', 16); // 15  
    //'FOX9' => 'F' => 15 (decimal value of 'F')
    // all characters from 'O' to end will be ignored once it encounters the out of range'O'
    // 'O' it is NOT in [0-9,A-F]
    

    Some more examples:

    parseInt('45', 13); // 57
    // both 4 and 5 are allowed in Radix is 13 [0-9,A-C]
    
    parseInt('1011', 2); // 11 (decimal NOT binary)
    
    parseInt(7,8); // 7
    // '7' => 7 in radix 8 [0 - 7]
    
    parseInt(786,8); // 7 
    // '78' => '7' => 7 (8 & next any numbers are ignored bcos 8 is NOT in [0-7])
    
    parseInt(76,8); // 62 
    // Both 7 & 6 are allowed '76' base 8 decimal conversion is 62 base 10 
    

提交回复
热议问题