1.toString() SyntaxError in Javascript

后端 未结 4 1329
误落风尘
误落风尘 2020-12-11 23:43

Why the first line below gives error although the second and third lines work fine?

1.toString(); // SyntaxError
(1).toString(); // OK
1[\'toString\'](); //          


        
相关标签:
4条回答
  • 2020-12-11 23:57

    The parser is trying to treat 1. as the start of a floating-point literal -- only toString turns it into an invalid number.

    Compare with:

    1.0.toString()
    
    0 讨论(0)
  • 2020-12-12 00:09

    The . presents ambiguity. Is it a decimal, or a property accessor?

    The interpreter sees it as a decimal, so you can use .. to allow both the decimal, then the property syntax.

    1..toString();
    

    Or use one of the other ways you show to resolve the ambiguity.

    0 讨论(0)
  • 2020-12-12 00:15

    In Javascript, using the dot (.) can be interpreted in one of two ways:

    1. As a Property Accessor (e.g., var prop = myObject.prop;).
    2. As part of a Floating-point Literal (e.g. var num = 1.5;).

    In the above case, the leading 1. in 1.toString() is interpreted as a floating point number, hence the error:

    SyntaxError: identifier starts immediately after numeric literal (learn more)

    This is the same error you get if you try and declare a variable that starts with a number: var 1person = 'john';

    To prevent the interpreter from seeing the 1. as a decimal and instead see it as accessing a property on our literal 1, there are several ways to accomplish this:

    // Via white-space after the numeric literal
    1 .toString();
    
    1
    .toString();
    
    // Via a grouping-operator, aka, parentheses
    // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Grouping_operator
    (1).toString();
    
    // Via an additional dot. Made clearer with parentheses as `(1.).toString()`
    1..toString();
    
    // Via an explicit fractional part (because `1. === 1.0`)
    1.0.toString();
    
    // Via bracket notation
    1['toString']();
    1.['toString']();
    1.0['toString']();
    
    0 讨论(0)
  • In (1).toString(), (1) forces it to evaluate before .toString() so it works. In 1.toString(), 1 is not a valid identifier so it does not work.

    0 讨论(0)
提交回复
热议问题