Why can't I access a property of an integer with a single dot?

前端 未结 4 1893
醉话见心
醉话见心 2020-11-22 05:41

If I try to write

3.toFixed(5)

there is a syntax error. Using double dots, putting in a space, putting the three in parentheses or using br

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 06:13

    You can't access it because of a flaw in JavaScript's tokenizer. Javascript tries to parse the dot notation on a number as a floating point literal, so you can't follow it with a property or method:

    2.toString(); // raises SyntaxError

    As you mentioned, there are a couple of workarounds which can be used in order make number literals act as objects too. Any of these is equally valid.

    2..toString(); // the second point is correctly recognized
    2 .toString(); // note the space left to the dot
    (2).toString(); // 2 is evaluated first
    

    To understand more behind object usage and properties, check out the Javascript Garden.

提交回复
热议问题