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

一些例子:

字符串(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

其他回答

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

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

我使用https://jsperf.com为以下用例创建了一个测试用例:

number + ''
`${number}`
String(number)
number.toString()

https://jsperf.com/number-string-conversion-speed-comparison

截至2018年7月24日,结果显示,在Chrome中,数字+”是最快的,在Firefox中,它与模板字符串文字相关联。

String(number)和number. tostring()都比最快的选项慢95%左右。

对于数字字面值,访问属性的点必须与十进制点区分。如果你想在数字文字123上调用to String(),这留给你以下选项:

123..toString()
123 .toString() // space before the dot 123.0.toString()
(123).toString()

在我看来,n.toString()因其清晰性而获得奖励,并且我不认为它会带来任何额外的开销。

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

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