将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?

一些例子:

字符串(n) n.toString() “”+n n+“”


当前回答

...JavaScript的解析器尝试进行解析 作为浮点字面值的数字上的点符号。

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

其他回答

只需使用模板文字语法:

`${this.num}`

方法toFixed()也可以解决这个问题。

var n = 8.434332;
n.toFixed(2)  // 8.43

我认为这取决于情况,但无论如何你可以使用. tostring()方法,因为它很容易理解。

...JavaScript的解析器尝试进行解析 作为浮点字面值的数字上的点符号。

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

其他答案已经涵盖了其他选项,但我更喜欢这个:

s = `${n}`

简短,简洁,已经在许多其他地方使用过(如果您使用的是现代框架/ ES版本),所以任何程序员都能理解它。

这(通常)不是很重要,但与其他方法相比,它似乎也是最快的方法之一。