简体   繁体   English

在 JavaScript 中将数字转换为字符串的最佳方法是什么?

[英]What's the best way to convert a number to a string in JavaScript?

What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc)?将数字转换为字符串的“最佳”方法是什么(在速度优势、清晰度优势、memory 优势等方面)?

Some examples:一些例子:

  1. String(n)

  2. n.toString()

  3. ""+n

  4. n+""

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 noted that 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根据这个测试http://jsben.ch/#/ghQYR在 Chrome 中num + ''似乎是最快的

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 倍。

在我看来n.toString()因其清晰而获奖,我认为它不会带来任何额外的开销。

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.最终,开发人员的时间比 CPU 时间更昂贵,所以我会以后者为代价来优化前者。 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.话虽这么说,在这种情况下,差异可能可以忽略不计,但如果不是,我确信有一些不错的 JavaScript 压缩器可以优化这类事情。

So, for the above reasons I'd go with: n.toString() or String(n) .因此,出于上述原因,我会选择: n.toString()String(n) String(n) is probably a better choice because it won't fail if n is null or undefined. String(n)可能是更好的选择,因为如果n为 null 或未定义,它不会失败。

...JavaScript's parser tries to parse the dot notation on a number as a floating point literal. ...JavaScript 的解析器尝试将数字上的点符号解析为浮点文字。

2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first

Source资源

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 fastest compared to other methods .并不是说它(通常)很重要,但与其他方法相比,它似乎也是最快的。

The below are the methods to convert an Integer to String in JS.下面是在 JS 中将Integer转换为String的方法。

The methods are arranged in the decreasing order of performance.这些方法按性能降序排列。

var num = 1

Method 1:方法一:

num = `${num}`

Method 2:方法二:

num = num + ''

Method 3:方法三:

num = String(num)

Method 4:方法四:

num = num.toString()

Note: You can't directly call toString() on a number.注意:您不能直接在数字上调用toString() 2.toString() will throw Uncaught SyntaxError: Invalid or unexpected token . 2.toString()会抛出Uncaught SyntaxError: Invalid or unexpected token

(The performance test results are given by @DarckBlezzer in his answer) (性能测试结果由@DarckBlezzer在他的回答中给出)

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}`;

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'

I used https://jsperf.com to create a test case for the following cases:我使用https://jsperf.com为以下情况创建了一个测试用例:

number + ''
`${number}`
String(number)
number.toString()

https://jsperf.com/number-string-conversion-speed-comparisonhttps://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% 左右。

性能测试,上面的描述

If you need to format the 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是要在小数点后显示的位数。

I recommended `${expression}` because you don't need to worry about errors.我推荐`${expression}` ,因为你不需要担心错误。

 [undefined,null,NaN,true,false,"2","",3].forEach(elem=>{ console.log(`${elem}`, typeof(`${elem}`)) }) /* output undefined string null string NaN string true string false string 2 string string 3 string */


Below you can test the speed.下面你可以测试一下速度。 but the order will affect the result.但顺序会影响结果。 (in StackOverflow) you can test it on your platform. (在 StackOverflow 中)你可以在你的平台上测试它。

 const testCases = [ ["${n}", (n) => `${n}`], // 👈 ['----', undefined], [`"" + n`, (n) => "" + n], [`'' + n`, (n) => '' + n], [`\`\` + n`, (n) => `` + n], [`n + ''`, (n) => n + ''], ['----', undefined], [`String(n)`, (n) => String(n)], ["${n}", (n) => `${n}`], // 👈 ['----', undefined], [`(n).toString()`, (n) => (n).toString()], [`n.toString()`, (n) => n.toString()], ] for (const [name, testFunc] of testCases) { if (testFunc === undefined) { console.log(name) continue } console.time(name) for (const n of [...Array(1000000).keys()]) { testFunc(n) } console.timeEnd(name) }

I'm going to re-edit this with more data when I have time to, for right now this is fine...当我有时间时,我将使用更多数据重新编辑它,因为现在这很好......

Test in nodejs v8.11.2: 2018/06/06在 nodejs v8.11.2 中测试:2018/06/06

 let i=0; console.time("test1") for(;i<10000000;i=i+1){ const string = "" + 1234; } console.timeEnd("test1") i=0; console.time("test1.1") for(;i<10000000;i=i+1){ const string = '' + 1234; } console.timeEnd("test1.1") i=0; console.time("test1.2") for(;i<10000000;i=i+1){ const string = `` + 1234; } console.timeEnd("test1.2") i=0; console.time("test1.3") for(;i<10000000;i=i+1){ const string = 1234 + ''; } console.timeEnd("test1.3") i=0; console.time("test2") for(;i<10000000;i=i+1){ const string = (1234).toString(); } console.timeEnd("test2") i=0; console.time("test3") for(;i<10000000;i=i+1){ const string = String(1234); } console.timeEnd("test3") i=0; console.time("test4") for(;i<10000000;i=i+1){ const string = `${1234}`; } console.timeEnd("test4") i=0; console.time("test5") for(;i<10000000;i=i+1){ const string = 1234..toString(); } console.timeEnd("test5") i=0; console.time("test6") for(;i<10000000;i=i+1){ const string = 1234 .toString(); } console.timeEnd("test6")

output输出

test1: 72.268ms
test1.1: 61.086ms
test1.2: 66.854ms
test1.3: 63.698ms
test2: 207.912ms
test3: 81.987ms
test4: 59.752ms
test5: 213.136ms
test6: 204.869ms

The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is String(x) .对于几乎所有可能的现有和未来情况(输入是数字、null、未定义、符号、其他任何东西),唯一有效的解决方案是String(x) Do not use 3 ways for simple operation, basing on value type assumptions, like "here I convert definitely number to string and here definitely boolean to string".不要使用 3 种方式进行简单操作,基于值类型假设,例如“这里我肯定将数字转换为字符串,这里肯定将布尔值转换为字符串”。

Explanation:解释:

String(x) handles nulls, undefined, Symbols, [anything] and calls .toString() for objects. String(x)处理空值、未定义、符号、[anything] 并为对象调用.toString()

'' + x calls .valueOf() on x (casting to number), throws on Symbols, can provide implementation dependent results. '' + x在 x 上调用.valueOf() (转换为数字),在符号上抛出,可以提供依赖于实现的结果。

x.toString() throws on nulls and undefined. x.toString()抛出空值和未定义。

Note: String(x) will still fail on prototype-less objects like Object.create(null) .注意: String(x)在没有原型的对象上仍然会失败,比如Object.create(null)

If you don't like strings like 'Hello, undefined' or want to support prototype-less objects, use the following type conversion function:如果您不喜欢 'Hello, undefined' 之类的字符串或想要支持无原型对象,请使用以下类型转换函数:

/**
 * Safely casts any value to string. Null and undefined are converted to ''.
 * @param  {*} value
 * @return {string}
 */
function string (str) {
  return value == null ? '' : (typeof value === 'object' && !value.toString ? '[object]' : String(value));
}

With number literals, the dot for accessing a property must be distinguished from the decimal dot.对于数字文字,访问属性的点必须与小数点区分开来。 This leaves you with the following options if you want to invoke to String() on the number literal 123:如果您想在数字文字 123 上调用 String(),则可以使用以下选项:

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

.toString() 是内置的类型转换函数,我不是这些细节的专家,但每当我们比较内置类型转换和显式方法时,总是首选内置的变通方法。

I like the first two since they're easier to read.我喜欢前两个,因为它们更容易阅读。 I tend to use String(n) but it is just a matter of style than anything else.我倾向于使用String(n) ,但这只是风格问题。

That is unless you have a line as那是除非你有一条线

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

which is very self explanatory这是非常不言自明的

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

If I had to take everything into consideration, I will suggest following如果我必须考虑所有因素,我会建议以下

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

IMHO, its the fastest way to convert to string.恕我直言,这是转换为字符串的最快方法。 Correct me if I am wrong.如果我错了,请纠正我。

If you are curious as to which is the most performant check this out where I compare all the different Number -> String conversions.如果您想知道哪个是性能最高的,请查看我比较所有不同的 Number -> String 转换的地方。

Looks like 2+'' or 2+"" are the fastest.看起来2+''2+""是最快的。

https://jsperf.com/int-2-string https://jsperf.com/int-2-string

We can also use the String constructor.我们还可以使用String构造函数。 According to this benchmark it's the fastest way to convert a Number to String in Firefox 58 even though it's slower than " + num in the popular browser Google Chrome.根据这个基准,它是 Firefox 58 中将数字转换为字符串的最快方法,尽管它比流行的浏览器 Google Chrome 中的" + num慢。

Method toFixed() will also solves the purpose.方法toFixed()也将解决目的。

var n = 8.434332;
n.toFixed(2)  // 8.43

You can call Number object and then call toString() .您可以调用Number对象,然后调用toString()

Number.call(null, n).toString()

You may use this trick for another javascript native objects.您可以将此技巧用于另一个 javascript 本机对象。

Just come across this recently, method 3 and 4 are not appropriate because how the strings are copied and then put together.最近刚碰到这个,方法3和4都不合适,因为字符串是如何复制然后放在一起的。 For a small program this problem is insignificant, but for any real web application this action where we have to deal with frequency string manipulations can affects the performance and readability.对于一个小程序来说,这个问题是微不足道的,但对于任何真正的 Web 应用程序来说,我们必须处理频率字符串操作的这个动作会影响性能和可读性。

Here is the link the read . 这是阅读的链接

It seems similar results when using node.js.使用 node.js 时结果似乎相似。 I ran this script:我运行了这个脚本:

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");

and got the following results:并得到以下结果:

❯ node testing.js
string concat testing: 2802.542ms
string obj testing: 3374.530ms
string both: 2660.023ms

Similar times each time I ran it.每次我运行它的时间都差不多。

Just use Template literal syntax:只需使用模板文字语法:

`${this.num}`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 JavaScript 中将字符串转换为数字的最快方法是什么? - What's the fastest way to convert String to Number in JavaScript? 用jQuery或Vanilla javascript在此URL字符串中获取数字的最佳方法是什么? - What's the best way to grab the number in this url string with jQuery or vanilla javascript? 在JavaScript / jQuery中,用逗号将数字转换为整数的最佳方法是什么? - In JavaScript / jQuery what is the best way to convert a number with a comma into an integer? JavaScript 中测试给定参数是否为平方数的最佳方法是什么? - What's the best way in JavaScript to test if a given parameter is a square number? 在javascript中打印带点的长数字的最佳方法是什么? - What's the best way to print out a long number with dots in javascript? 查找启动字符串的制表符数量的最佳/最快方法是什么? - What's the best/fastest way to find the number of tabs to start a string? 在 JavaScript 中将数字转换为百分比的最简单方法是什么? - What's the easiest way to convert a number to a percentage in JavaScript? Javascript字符串替换 - 这是最好的方法吗? - Javascript string replacement - what's the best way to do this? 在 JavaScript 中,将 NodeList 转换为数组的最佳方法是什么? - In JavaScript, what is the best way to convert a NodeList to an array? 从字符串转换为 javascript 对象的最佳方法 - best way to convert from string to javascript object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM