parseInt(null, 24) === 23… wait, what?

前端 未结 6 2022
栀梦
栀梦 2020-12-12 10:08

Alright, so I was messing around with parseInt to see how it handles values not yet initialized and I stumbled upon this gem. The below happens for any radix 24 or above.

6条回答
  •  眼角桃花
    2020-12-12 10:23

    It's converting null to the string "null" and trying to convert it. For radixes 0 through 23, there are no numerals it can convert, so it returns NaN. At 24, "n", the 14th letter, is added to the numeral system. At 31, "u", the 21st letter, is added and the entire string can be decoded. At 37 on there is no longer any valid numeral set that can be generated and NaN is returned.

    js> parseInt(null, 36)
    1112745
    
    >>> reduce(lambda x, y: x * 36 + y, [(string.digits + string.lowercase).index(x) for x in 'null'])
    1112745
    

提交回复
热议问题