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

一些例子:

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


当前回答

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

number.toFixed( [digits] )

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

其他回答

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

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

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

当使用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

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

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

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

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

number.toFixed( [digits] )

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

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