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

一些例子:

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


当前回答

你可以调用Number对象,然后调用toString()。

号码。调用(null, n) .toString ()

你可以将这个技巧用于其他javascript原生对象。

其他回答

如果需要将结果格式化为特定的小数位数,例如表示货币,则需要类似toFixed()方法的东西。

number.toFixed( [digits] )

数字是小数点后要显示的位数。

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

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

如果你好奇哪一个是性能最好的,看看我比较了所有不同的Number ->字符串转换。

看起来2+"或2+""是最快的。

https://jsperf.com/int-2-string

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

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

我喜欢前两个,因为它们更容易阅读。我倾向于使用String(n),但这只是一个风格问题。

除非你有一行

var n = 5;
console.log ("the number is: " + n);

这不言自明吗