将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
当前回答
当使用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
每次运行的时间都差不多。
其他回答
你可以调用Number对象,然后调用toString()。
号码。调用(null, n) .toString ()
你可以将这个技巧用于其他javascript原生对象。
对于数字字面值,访问属性的点必须与十进制点区分。如果你想在数字文字123上调用to String(),这留给你以下选项:
123..toString()
123 .toString() // space before the dot 123.0.toString()
(123).toString()
方法toFixed()也可以解决这个问题。
var n = 8.434332;
n.toFixed(2) // 8.43
开玩笑的意味很明显:
var harshNum = 108;
"".split.call(harshNum,"").join("");
或者在ES6中,你可以简单地使用模板字符串:
var harshNum = 108;
`${harshNum}`;
我喜欢前两个,因为它们更容易阅读。我倾向于使用String(n),但这只是一个风格问题。
除非你有一行
var n = 5;
console.log ("the number is: " + n);
这不言自明吗