繁体   English   中英

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

[英]What's the fastest way to convert String to Number in JavaScript?

任何数字,都是数字。 字符串看起来像一个数字,它是数字。 其他一切,它都是NaN。

'a' => NaN
'1' => 1
1 => 1

据我所知,有4种方法可以做到这一点。

Number(x);
parseInt(x, 10);
parseFloat(x);
+x;

通过我做的这个快速测试,它实际上取决于浏览器。

https://jsben.ch/NnBKM

Implicit在 3 个浏览器上标记为最快,但它使代码难以阅读……所以选择你喜欢的任何东西!

至少有 5 种方法可以做到这一点:

如果您只想转换为整数,另一种快速(且简短)的方法是双位非(即使用两个波浪号字符):

例如

~~x;

参考:http: //james.padolsey.com/cool-stuff/double-bitwise-not/

到目前为止,我所知道的将字符串转换为数字的 5 种常用方法都有其不同(有更多的按位运算符有效,但它们都给出与~~相同的结果)。 此 JSFiddle 显示了您可以在调试控制台中预期的不同结果:http: //jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/

var values = ["123",
          undefined,
          "not a number",
          "123.45",
          "1234 error",
          "2147483648",
          "4999999999"
          ];

for (var i = 0; i < values.length; i++){
    var x = values[i];

    console.log(x);
    console.log(" Number(x) = " + Number(x));
    console.log(" parseInt(x, 10) = " + parseInt(x, 10));
    console.log(" parseFloat(x) = " + parseFloat(x));
    console.log(" +x = " + +x);
    console.log(" ~~x = " + ~~x);
}

调试控制台:

123
  Number(x) = 123
  parseInt(x, 10) = 123
  parseFloat(x) = 123
  +x = 123
  ~~x = 123
undefined
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
null
  Number(x) = 0
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = 0
  ~~x = 0
"not a number"
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
123.45
  Number(x) = 123.45
  parseInt(x, 10) = 123
  parseFloat(x) = 123.45
  +x = 123.45
  ~~x = 123
1234 error
  Number(x) = NaN
  parseInt(x, 10) = 1234
  parseFloat(x) = 1234
  +x = NaN
  ~~x = 0
2147483648
  Number(x) = 2147483648
  parseInt(x, 10) = 2147483648
  parseFloat(x) = 2147483648
  +x = 2147483648
  ~~x = -2147483648
4999999999
  Number(x) = 4999999999
  parseInt(x, 10) = 4999999999
  parseFloat(x) = 4999999999
  +x = 4999999999
  ~~x = 705032703

~~x版本在“更多”情况下会产生一个数字,而其他情况通常会导致undefined ,但它会因无效输入而失败(例如,如果字符串在有效数字包含非数字字符,它将返回0 )。

溢出

请注意: ~~可能会发生整数溢出和/或位截断,但不会发生其他转换。 虽然输入如此大的值并不常见,但您需要注意这一点。 更新示例以包含更大的值。

一些 Perf 测试表明标准的parseIntparseFloat函数实际上是最快的选项,大概是由浏览器高度优化的,但这完全取决于您的要求,因为所有选项都足够快:http: //jsperf.com/best-of-string -to-number-conversion/37

这一切都取决于性能测试的配置方式,因为某些显示 parseInt/parseFloat 的速度要慢得多。

我的理论是:

  • 谎言
  • 织补线
  • 统计数据
  • JSPerf 结果:)

使用+运算符为字符串添加前缀。

console.log(+'a') // NaN
console.log(+'1') // 1
console.log(+1) // 1

将字符串转换为整数的一种快速方法是使用按位或,如下所示:

x | 0

虽然这取决于它是如何实现的,但理论上它应该相对较快(至少与+x一样快),因为它首先将x转换为一个数字,然后执行一个非常有效的 or。

这是一个简单的方法: var num = Number(str); 在此示例中, str是包含字符串的变量。 你可以打开测试看看它是如何工作的:谷歌浏览器开发者工具,然后去控制台粘贴下面的代码。 阅读评论以更好地了解转换是如何完成的。

// Here Im creating my variable as a string
var str = "258";


// here im printing the string variable: str
console.log ( str );


// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);


// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);

我发现num * 1简单、清晰,适用于整数和浮点数......

这可能不是那么快,但具有确保您的数字至少为某个值(例如 0)或最多为某个值的额外好处:

Math.max(input, 0);

如果您需要确保最小值,通常您会这样做

var number = Number(input);
if (number < 0) number = 0;

Math.max(..., 0)使您免于编写两个语句。

您可以尝试使用我们刚刚正式发布的度量和数据类型转换库UnitOf UnitOf 速度超快,体积小,并且在转换任何数据类型时都非常高效,而不会抛出错误或 null/undefined。 当转换不成功时,将返回您定义的默认值或 UnitOf 的默认值。

//One liner examples
UnitOf.DataType("12.5").toFloat(); //12.5 of type Float is returned. 0 would be returned if conversion failed.
UnitOf.DataType("Not A Num").toInt(10); //10 of type Int is returned as the conversion failed.

//Or as a variable
var unit = UnitOf.DataType("12.5");
unit.toInt(5); //12.5 of type Float is returned. 5 would be returned if the conversion failed.
unit.toFloat(8); // 12 of type Int is returned. 8 would be returned if the conversion failed.

最快的方法是使用-0:

const num = "12.34" - 0;

将字符串转换为数字的 7 种方法:

let str = "43.2"

1. Number(str) => 43.2
2. parseInt(str) => 43
3. parseFloat(str) => 43.2
4. +str => 43
5.str str * 1 => 43.2
6. Math.floor(str) => 43
7. ~~str => 43

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM