将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(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
源
其他回答
下面是在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在他的回答中给出)
最近刚遇到这个,方法3和4是不合适的,因为字符串是如何复制然后放在一起的。对于一个小程序来说,这个问题是微不足道的,但是对于任何真实的web应用程序来说,我们必须处理频率字符串操作的这个操作可能会影响性能和可读性。
这是阅读的链接。
当使用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
每次运行的时间都差不多。
如果我必须把所有的事情都考虑进去的话,我还是建议跟随
var myint = 1;
var mystring = myint + '';
/*or int to string*/
myint = myint + ''
恕我直言,这是转换为字符串的最快方式。如果我错了,请指正。
在我看来,n.toString()因其清晰性而获得奖励,并且我不认为它会带来任何额外的开销。