Why doesn't an octal literal as a string cast to a number?

后端 未结 3 1564
甜味超标
甜味超标 2020-12-08 21:00

In JavaScript, why does an octal number string cast as a decimal number? I can cast a hex literal string using Number() or +, why not an octal?

3条回答
  •  借酒劲吻你
    2020-12-08 21:45

    Because you're not actually performing casting in the proper sense (JS doesn't have casting) - it's just type juggling.

    When you have any literal in Javascript and enact a method on it, an object is created behind the scenes for you.

    "foo".toUpperCase() for example, is replaced by the evaluation of code that would roughly look like this new String( "foo" ).toUpperCase();

    Since strings can't be evaluated with a unary + operator, JS converts your string to a number - and it doesn't use parseInt() or parseFloat() internally - you guessed it - it uses Number().

    So, the value you see is the what you'd see from the return of Number(), which doesn't appear to assume octals.

提交回复
热议问题