Home  >  Article  >  Web Front-end  >  Parsing the ambiguity of the dot "." in JavaScript_javascript skills

Parsing the ambiguity of the dot "." in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:11:161315browse

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 almost nothing difficult to understand, but the following question is interesting.

Copy code The code is as follows:

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

Firebug is as follows

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 The code is as follows:

(1).toString();

You can also write it like this, but it is harder to understand
Copy code The code is as follows:

1..toString();

The reason why it can run in browsers is because the JS engines of each browser put " 1..toString()” is understood as “1.0.toString()”. The first dot here is semantic 1, and the second dot is semantic 2.

There is a weirder way of writing, but no error is reported

Copy the code The code is as follows:

1 .toString(); // Note that there is a space before the dot symbol

Obviously, the dot symbol here is semantic 2, that is, the JS engine will ignore the space before the dot operator. In fact, no matter Leading and trailing spaces will be ignored. As follows
Copy the code The code is as follows:

1 . toString(); // before and after the dot There is a space
1 . toString(); // There are two spaces before and after the dot
1 .toString(); // There is a tab before the dot
1 . toString(); / There is a tab before and after the / period

The JS engine will not only ignore spaces, but also ignore tabs.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn