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

一些例子:

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


当前回答

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

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

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

其他回答

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

除非你有一行

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

这不言自明吗

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

下面是在JS中将Integer转换为String的方法。

这些方法按性能递减的顺序排列。

var num = 1

方法1:

num = `${num}`

方法2:

num = num + ''

方法3:

num = String(num)

方法4:

num = num.toString()

注意:你不能对一个数字直接调用toString()。2.toString()将抛出Uncaught SyntaxError:无效或意外令牌。

(性能测试结果由@DarckBlezzer在他的回答中给出)

开玩笑的意味很明显:

var harshNum = 108;
"".split.call(harshNum,"").join("");

或者在ES6中,你可以简单地使用模板字符串:

var harshNum = 108;
`${harshNum}`;

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

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