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

一些例子:

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


当前回答

只需使用模板文字语法:

`${this.num}`

其他回答

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

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

是这样的:

var foo = 45;
var bar = '' + foo;

实际上,尽管我这样做是为了简单方便,经过1000次迭代后它看起来是为了原始速度。tostring()有一个优势

请参阅这里的性能测试(不是我写的,而是我自己写的时候发现的): http://jsben.ch/#/ghQYR

基于上面的JSPerf测试的最快速度:str = num.toString();

值得注意的是,当您考虑到它可以在0.1秒内以任何方式进行100万次转换时,速度上的差异并不太显著。

更新:不同浏览器的速度似乎差别很大。在Chrome中num +”似乎是最快的基于这个测试http://jsben.ch/#/ghQYR

更新2:根据我上面的测试,应该注意到Firefox 20.0.1执行. tostring()的速度比“+ num”示例慢了大约100倍。

我使用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%左右。

只需使用模板文字语法:

`${this.num}`

将任何变量转换为字符串的最简单方法是向该变量添加一个空字符串。

5.41 + ''    // Result: the string '5.41'
Math.PI + '' // Result: the string '3.141592653589793'