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

前端 未结 6 2016
栀梦
栀梦 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:37

    parseInt( null, 24 ) === 23
    

    Is equivalent to

    parseInt( String(null), 24 ) === 23
    

    which is equivalent to

    parseInt( "null", 24 ) === 23
    

    The digits for base 24 are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, ..., n.

    The language spec says

    1. If S contains any character that is not a radix-R digit, then let Z be the substring of S consisting of all characters before the first such character; otherwise, let Z be S.

    which is the part that ensures that C-style integer literals like 15L parse properly, so the above is equivalent to

    parseInt( "n", 24 ) === 23
    

    "n" is the 23-rd letter of the digit list above.

    Q.E.D.

提交回复
热议问题