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?
世界只因有你2017-05-19 10:20:07
I saw this explanation: Numeric literals directly call methods. As long as the JavaScript engine does not confuse the decimal point with the dot operator of the object, various writing methods can be used. JavaScript will understand the first point as a decimal point (i.e. 10.0), understand the second point as calling object properties, so as to obtain the correct result.
My opinion: As long as the meaning of the dot is unambiguous, the compiler can understand it correctly.
Obviously the brackets are added and the following .
是 点运算符
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
The point after the floating point number must no longer refer to the decimal point, but to 点运算符
obj[key] This way you can find the attribute named key in obj.
The reason is that the compiler will have two interpretations when seeing this:
1. (10.0).toString();
2. 10 .toString();
phpcn_u15822017-05-19 10:20:07
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.