JavaScript 函数 toString

6
请看下面的代码:
2.toString();   // error
2..toString();  // "2"
2...toString(); // error

我想知道为什么2..toString()可以无错误运行,并且它的运行会发生什么?

有人能解释一下吗?


好奇你是在哪里找到这个示例代码的。令人惊讶的是,它基本上与@Nikolay答案中提供的示例链接相同... - Zach Lysobey
@Zach L 我曾经在其他地方看到过它,但并不总是理解。今天,我又看到了它。所以我来这里寻求答案。当我打开 Nikolay 提供的链接时,这确实让我感到惊讶,因为我刚刚看到了另一个非常相似的网站。但它是另一种语言而不是英语。 - Joyce Lee
可能是重复的问题:调用数字字面值的成员函数 - gcampbell
1个回答

8

http://shamansir.github.io/JavaScript-Garden/en/#object

A common misconception is that number literals cannot be used as objects. That is because a flaw in JavaScript's parser tries to parse the dot notation on a number as a floating point literal.

2.toString(); // raises SyntaxError

There are a couple of workarounds that can be used to make number literals act as objects too.

2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first

@Nikolay Tlnv:谢谢。当JavaScript解析器遇到2.toString()时,它不知道如何将点解析为2.|toString()还是2|.toString()。如果在点的左侧还有另一个点或空格,解析器可以将其视为某种方式。这样对吗? - Joyce Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接