difference between numbers using or without using variable

后端 未结 3 1651
盖世英雄少女心
盖世英雄少女心 2020-12-21 01:47

What\'s the difference between the following code?

var a = 1;
a.toString(); // outputs: \"1\"

But this throws an error:

1.t         


        
相关标签:
3条回答
  • 2020-12-21 02:06

    The toString() method returns a string representing object.

    So when you call:

    a.toString();
    

    You are actually operating on an object. You are actually creating a built-in object when you define a variable(in this case it is a number).

    When you do this:

    1.toString();
    

    toString() doesn't see 1 as an object or a variable(both are the same in this scenario) because it fails the rule:

    Variable must begin with a letter

    Here 1 doesn't begin with a letter. So toString() knows it is not operating on an object and throws an error.

    0 讨论(0)
  • 2020-12-21 02:09

    With method invocations, it is important to distinguish between the floating-point dot and the method invocation dot. Thus, you cannot write 1.toString(); you must use one of the following alternatives:

    1..toString()
    1 .toString() //space before dot
    (1).toString()
    1.0.toString()
    
    0 讨论(0)
  • 2020-12-21 02:10

    Try to Change the Syntax,

    (1).toString()

    Numbers can have decimals, so the syntax for ending in a decimal is a bit ambiguous when you go to parse the code, use parenthesis to be valid. It's a bit clearer when you see that this is also valid:

    (1.).toString()

    However with just

    1.toString() it's trying to parse as a number with a decimal, and it fails.

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