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

一些例子:

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


当前回答

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

除非你有一行

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

这不言自明吗

其他回答

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

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

我认为这取决于情况,但无论如何你可以使用. tostring()方法,因为它很容易理解。

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

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

显式转换对于语言新手来说非常清楚。正如其他人所建议的那样,如果开发人员不知道强制规则,使用类型强制将导致歧义。最终,开发人员的时间比CPU的时间更昂贵,所以我将以后者为代价来优化前者。话虽如此,在这种情况下,差异可能可以忽略不计,但如果不是这样,我相信有一些不错的JavaScript压缩器可以优化这类事情。

因此,出于上述原因,我选择:n. tostring()或String(n)。String(n)可能是一个更好的选择,因为如果n为空或未定义,它不会失败。

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

除非你有一行

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

这不言自明吗