Parsing the polysemy of the dot '. 'in JavaScript

  • 2020-03-30 00:42:55
  • OfStack

The dot ". "has two semantics in JavaScript

Semantics 1, represents the decimal point (floating point number) in arithmetic, such as 2.5

Take object properties and methods, such as []. Push (2)

There is hardly anything difficult about this, but the following question is interesting.


//How will this line of code execute
1.toString(); 

Firebug in the following

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201312/20131202100635.png ">

The dot here represents the above semantic 1, so the dot must be followed by a number. In this case, the dot is followed by toString. The syntax is wrong.

The solution is as simple as adding a brace


(1).toString(); 

I could have written it this way, but it's a little harder to understand

1..toString();

The reason it works in all browsers is that each browser's JS engine USES "1.. ToString () is understood as "1.0.tostring ()". Here the first dot is semantic 1 and the second dot is semantic 2.

There's even a weirder way to write it, and there's no error


1 .toString(); //Notice that the dot is preceded by a space

Obviously, the dot sign here is semantic 2, which means that the JS engine ignores the Spaces in front of the dot operator, regardless of the Spaces before and after. The following

1 . toString(); //There is a space before and after the dot
1  .  toString(); //There are two Spaces before and after the dot
1    .toString(); //There's a TAB before the dot
1    .    toString(); //There's a TAB before and after the dot

Not only does the JS engine ignore Spaces, it also ignores tabs.


Related articles: