在 JavaScript 中将数字转换为字符串的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5765398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to convert a number to a string in JavaScript?
提问by Pacerier
What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
将数字转换为字符串的“最佳”方法是什么(在速度优势、清晰度优势、内存优势等方面)?
Some examples:
一些例子:
String(n)
n.toString()
""+n
n+""
String(n)
n.toString()
""+n
n+""
回答by scunliffe
like this:
像这样:
var foo = 45;
var bar = '' + foo;
Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()
实际上,尽管我通常为了简单方便而这样做,但对于原始速度而言,超过 1,000 次的迭代似乎是有优势的.toString()
See Performance tests here (not by me, but found when I went to write my own): http://jsben.ch/#/ghQYR
在这里查看性能测试(不是我做的,而是我自己写的时候发现的):http: //jsben.ch/#/ghQYR
Fastest based on the JSPerf test above: str = num.toString();
最快基于上面的 JSPerf 测试: str = num.toString();
It should be notedthat the difference in speed is not overly significant when you consider that it can do the conversion any way 1 Million times in 0.1 seconds.
应该注意的是,当您考虑到它可以在 0.1 秒内以任何方式进行100 万次转换时,速度上的差异并不过分显着。
Update:The speed seems to differ greatly by browser. In Chrome num + ''
seems to be fastest based on this test http://jsben.ch/#/ghQYR
更新:速度似乎因浏览器而异。num + ''
基于这个测试,在 Chrome 中似乎是最快的http://jsben.ch/#/ghQYR
Update 2:Again based on my test above it should be noted that Firefox 20.0.1 executes the .toString()
about 100 times slower than the '' + num
sample.
更新 2:再次基于我上面的测试,应该注意到 Firefox 20.0.1 的执行.toString()
速度比'' + num
示例慢约 100 倍。
回答by CarlosZ
In my opinion n.toString()
takes the prize for its clarity, and I don't think it carries any extra overhead.
在我看来n.toString()
,它因其清晰性而获奖,我认为它不会带来任何额外的开销。
回答by Bryan Kyle
Explicit conversions are very clear to someone that's new to the language. Using type coercion, as others have suggested, leads to ambiguity if a developer is not aware of the coercion rules. Ultimately developer time is more costly than CPU time, so I'd optimize for the former at the cost of the latter. That being said, in this case the difference is likely negligible, but if not I'm sure there are some decent JavaScript compressors that will optimize this sort of thing.
对于语言的新手来说,显式转换非常清楚。正如其他人所建议的那样,如果开发人员不了解强制规则,则使用类型强制会导致歧义。最终开发人员时间比 CPU 时间更昂贵,所以我会以后者为代价来优化前者。话虽如此,在这种情况下,差异可能可以忽略不计,但如果不是,我确信有一些不错的 JavaScript 压缩器可以优化这类事情。
So, for the above reasons I'd go with: n.toString()
or String(n)
. String(n)
is probably a better choice because it won't fail if n
is null or undefined.
因此,出于上述原因,我会选择:n.toString()
或String(n)
。 String(n)
可能是更好的选择,因为如果n
为 null 或未定义,它不会失败。
回答by Mohammad Arif
回答by cssimsek
Tongue-in-cheek obviously:
明显是在说笑:
var harshNum = 108;
"".split.call(harshNum,"").join("");
Or in ES6 you could simply use template strings:
或者在 ES6 中你可以简单地使用模板字符串:
var harshNum = 108;
`${harshNum}`;
回答by johndodo
Other answers already covered other options, but I prefer this one:
其他答案已经涵盖了其他选项,但我更喜欢这个:
s = `${n}`
Short, succinct, already used in many other places (if you're using a modern framework / ES version) so it's a safe bet any programmer will understand it.
简短,简洁,已经在许多其他地方使用(如果您使用的是现代框架/ES 版本),因此可以肯定任何程序员都会理解它。
Not that it (usually) matters much, but it also seems to be among the fastestcompared to other methods.
回答by sgokhales
The simplest way to convert any variable to a string is to add an empty string to that variable.
将任何变量转换为字符串的最简单方法是向该变量添加一个空字符串。
5.41 + '' // Result: the string '5.41'
Math.PI + '' // Result: the string '3.141592653589793'
回答by Tim
If you need to formatthe result to a specific number of decimal places,for example to represent currency, you need something like the toFixed()
method.
如果您需要将结果格式化为特定的小数位数,例如表示货币,您需要类似toFixed()
方法的东西。
number.toFixed( [digits] )
digits
is the number of digits to display after the decimal place.
digits
是小数点后显示的位数。
回答by Erick
I used https://jsperf.comto create a test case for the following cases:
我使用https://jsperf.com为以下案例创建了一个测试用例:
number + ''
`${number}`
String(number)
number.toString()
https://jsperf.com/number-string-conversion-speed-comparison
https://jsperf.com/number-string-conversion-speed-comparison
As of 24th of July, 2018 the results say that number + ''
is the fastest in Chrome, in Firefox that ties with template string literals.
截至 2018 年 7 月 24 日,结果表明这number + ''
是 Chrome 中最快的,在与模板字符串文字相关的 Firefox 中。
Both String(number)
, and number.toString()
are around 95% slower than the fastest option.
两者String(number)
,并且number.toString()
比最快的选项慢95%左右。
回答by Mubeen Khan
.toString() is the built-in typecasting function, I'm no expert to that details but whenever we compare built-in type casting verse explicit methodologies, built-in workarounds always preferred.
.toString() 是内置的类型转换函数,我不是那个细节的专家,但是每当我们比较内置的类型转换和显式方法时,内置的变通方法总是首选。