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

一些例子:

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

其他回答

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

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

如果我必须把所有的事情都考虑进去的话,我还是建议跟随

var myint = 1;
var mystring = myint + '';
/*or int to string*/
myint = myint + ''

恕我直言,这是转换为字符串的最快方式。如果我错了,请指正。

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

除非你有一行

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

这不言自明吗

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

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

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

当使用node.js时,结果似乎类似。我运行这个脚本:

let bar;
let foo = ["45","foo"];

console.time('string concat testing');
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo;
}
console.timeEnd('string concat testing');


console.time("string obj testing");
for (let i = 0; i < 10000000; i++) {
    bar = String(foo);
}
console.timeEnd("string obj testing");

console.time("string both");
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo + "";
}
console.timeEnd("string both");

并得到以下结果:

❯ node testing.js
string concat testing: 2802.542ms
string obj testing: 3374.530ms
string both: 2660.023ms

每次运行的时间都差不多。