The dot "." has two semantics in JavaScript
Semantics 1. Represents the decimal point (floating point number) in arithmetic, such as 2.5
Semantics 2. Get object attributes and methods, such as [].push(2)
There is hardly anything difficult to understand, but the following question is interesting.
Copy the code code as follows:
// How will this line of code be executed?
1.toString();
As follows in Firebug
The dot here expresses the above-mentioned semantics 1, so the dot must be followed by a number. What follows here is toString, and the reporting syntax is wrong.
The solution is very simple, such as adding parentheses
Copy the code code as follows:
(1).toString();
You can still write it like this, but it’s harder to understand
Copy the code code as follows:
1..toString();
The reason why it can run in browsers is because each browser JS engine understands "1..toString()" as "1.0.toString()". The first dot here is semantic 1, and the second dot is semantic 2.
There is an even weirder way of writing it, but no error is reported.
Copy the code code as follows:
1.toString(); // Note that there is a space before the period
Obviously, the dot here is semantic 2, that is, the JS engine will ignore the spaces before the dot operator. In fact, no matter the spaces before or after it, it will be ignored. as follows
Copy the code code as follows:
1. toString(); // There is a space before and after the period
1. toString(); // There are two spaces before and after the period.
1.toString(); // There is a tab before the period
1. toString(); // There is a tab before and after the dot.
The JS engine will not only ignore spaces, but also ignore tabs.