Directly call the method on the Number prototype, as follows:
10.toString();
An error will be reported: Uncaught SyntaxError: Invalid or unexpected token
However, there will be no error if you call floating point numbers directly
10.1.toString();//"10.1"
I saw this explanation:
Number literals directly call methods. As long as the JavaScript engine does not confuse the decimal point and the dot operator of the object, various writing methods can be used, and JavaScript will understand the first point. into a decimal point (i.e. 10.0), and understand the second point as calling the object property to get the correct result.
For example, the following calling methods are correct
(10).toString(2)
10..toString(2) // "1010"
10 .toString(2) // "1010"
10.0.toString(2) // "1010"
10['toString'](2) // "1010"
But I don’t understand the working principle here.
I initially guessed that it was due to the priority of the bracket or dot operator. Did I convert 10 to number first?
But I don’t think this can be explained.
Could you please tell me why an error occurs when calling prototype methods directly on integers, but not on floating point numbers?
Why can the prototype method of an integer be called through the methods listed above?
My opinion: As long as the meaning of the dot is unambiguous, the compiler can understand it correctly.
(10).toString(2) // "1010"
Obviously the brackets are added and the following
.
是点运算符
10..toString(2) // "1010"
There is no number with two decimal points, so this also refers to
点运算符
So this 10..toString(2) can actually be boiled down to the following
10.0.toString(2) // "1010"
The point after the floating point number must no longer refer to the decimal point, but to
点运算符
10['toString'](2) // "1010"
obj[key] This way you can find the attribute named key in obj.
10.toString() Reason for error
The reason is that the compiler will have two interpretations when seeing this:
Compilation principle, when the engine starts to parse numbers,
.
is legal, so it will be given priority as a decimal point. The above solutions all tell the parser "finished reading the numbers" and start reading the next token.