Why does 10..toString() work, but 10.toString() do

2020-01-24 11:07发布

Possible Duplicate:
Usage of toString in JavaScript

152..toString(2)

correctly creates the binary string "10011000", but

152.toString(2)

throws an exception

"SyntaxError: identifier starts immediately after numeric literal"

Why? The latter syntax actually sounds more correct while the former looks very odd!

3条回答
我只想做你的唯一
2楼-- · 2020-01-24 11:41

The lexer (aka "tokenizer") when reading a new token, and upon first finding a digit, will keep consuming characters (i.e. digits or one dot) until it sees a character that is not part of a legal number.

<152.> is a legal token (the trailing 0 isn't required) but <152..> isn't, so your first example reduces to this series of tokens:

<152.> <.> <toString> <(> <2> <)>

which is the legal (and expected) sequence, whereas the second looks like

<152.> <toString> <(> <2> <)>

which is illegal - there's no period token separating the Number from the toString call.

查看更多
Fickle 薄情
3楼-- · 2020-01-24 11:46

10. is a float number an you can use toString on float

eg.

parseFloat("10").toString() // "10"
查看更多
forever°为你锁心
4楼-- · 2020-01-24 11:56

A . after a number might seem ambiguous. Is it a decimal or an object member operator?

However, the interpreter decides that it's a decimal, so you're missing the member operator.

It sees it as this:

(10.)toString();  // invalid syntax

When you include the second ., you have a decimal followed by the member operator.

(10.).toString();

@pedants and downvoters

The . character presents an ambiguity. It can be understood to be the member operator, or a decimal, depending on its placement. If there was no ambiguity, there would be no question to ask.

The specification's interpretation of the . character in that particular position is that it will be a decimal. This is defined by the numeric literal syntax of ECMAScript.

Just because the specification resolves the ambiguity for the JS interpreter, doesn't mean that the ambiguity of the . character doesn't exist at all.

查看更多
登录 后发表回答