1.toString() SyntaxError in Javascript

后端 未结 4 1358
误落风尘
误落风尘 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-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']();
    

提交回复
热议问题