JavaScript에서 문자열을 숫자로 변환하는 가장 빠른 방법은 무엇입니까?
어떤 숫자 든 숫자입니다. 문자열은 숫자처럼 보입니다. 숫자입니다. 그 밖의 모든 것들은 NaN으로갑니다.
'a' => NaN
'1' => 1
1 => 1
내가 아는 한 4 가지 방법이 있습니다.
Number(x);
parseInt(x, 10);
parseFloat(x);
+x;
이 빠른 테스트를 통해 실제로 브라우저에 따라 다릅니다.
http://jsperf.com/best-of-string-to-number-conversion/2
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문자열이 숫자가 아닌 문자가 포함 된 경우 후 유효한 숫자).
과다
Please note: Integer overflow and/or bit truncation can occur with ~~, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.
Some Perf tests indicate that the standard parseInt and parseFloat functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37
This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.
My theory is:
- Lies
- Darn lines
- Statistics
- JSPerf results :)
A fast way to convert strings to an integer is to use a bitwise or, like so:
x | 0
While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x) since it will first cast x to a number and then perform a very efficient or.
Prefix the string with the + operator.
console.log(+'a') // NaN
console.log(+'1') // 1
console.log(+1) // 1
Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.
// 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);
This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:
Math.max(input, 0);
If you need to ensure a minimum value, usually you'd do
var number = Number(input);
if (number < 0) number = 0;
Math.max(..., 0) saves you from writing two statements.
I find that num * 1 is simple, clear, and works for integers and floats...
You can try using UnitOf, a measurement and data type conversion library we just officially released! UnitOf is super fast, small in size, and efficient at converting any data type without ever throwing an error or null/undefined. Default values you define or UnitOf's defaults are returned when a conversion is unsuccessful.
//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.
'Programing' 카테고리의 다른 글
| Logcat이 내 로그 호출을 표시하지 않습니다 (0) | 2020.07.23 |
|---|---|
| 상태 코드가있는 ASP.NET Core 반환 JSON (0) | 2020.07.23 |
| AngularJS-라디오 버튼 선택시 트리거 (0) | 2020.07.23 |
| 이 쿼리로 페이징 (건너 뛰기 / 취소) 기능 구현 (0) | 2020.07.23 |
| Visual Studio 디버그 모드에서 개체 값 복사 (0) | 2020.07.23 |