Programing

JavaScript에서 parseInt (string)과 Number (string)의 차이점은 무엇입니까?

lottogame 2020. 4. 28. 08:18
반응형

JavaScript에서 parseInt (string)과 Number (string)의 차이점은 무엇입니까? [복제]


이 질문에는 이미 답변이 있습니다.

차이점은 무엇이며 parseInt(string)그리고 Number(string)자바 스크립트는?


parseInt("123hui")

123을 반환

Number("123hui")

보고 NaN

parseInt(), 숫자가 아닌 첫 번째 숫자까지 구문 분석하고 구문 분석 한 내용을 리턴합니다. Number()전체 문자열을 부동 소수점 BTW 일 수있는 숫자로 변환하려고합니다.


편집 # 1 : Lucero는와 함께 사용할 수있는 기수에 대해 언급했습니다 parseInt(). 그에 관한 한, 아래 의 의사의 답변을 참조하십시오 (나는 여기서 그것을 복사하지 않을 것입니다, 의사는 명성의 공정한 몫을 가질 것입니다 ...).


편집 # 2 : 사용 사례와 관련하여 이미 행 사이에 작성되었습니다. Number()주어진 문자열이 숫자, 부동 또는 정수를 완전히 나타내는 지 간접적으로 확인하려는 경우에 사용하십시오 . parseInt()/parseFloat()숫자 값이 멈출 때 (기수!) 파싱하고 멈추기 때문에 엄격하지 않습니다. 앞면에 숫자가있을 때 숫자 값이 필요할 때 유용합니다 ( parseInt("hui")또한 반환합니다 NaN). 그리고 가장 큰 차이점은 주어진 문자열을 Number()알지 못하고 parseInt()간접적으로 추측 할 수있는 기수의 사용입니다 (때로는 이상한 결과를 초래할 수 있음).


첫 번째는 두 가지 매개 변수를 사용합니다.

parseInt(string, radix)

기수 매개 변수는 사용할 숫자 시스템을 지정하는 데 사용됩니다. 예를 들어 기수 16 (16 진수)은 문자열의 숫자를 16 진수에서 10 진수로 구문 분석해야 함을 나타냅니다.

기수 매개 변수를 생략하면 JavaScript는 다음을 가정합니다.

  • 문자열이 "0x"로 시작하면
    기수는 16 (16 진수)입니다.
  • 문자열이 "0"으로 시작하면 기수가 8 (8 진수)입니다. 이 기능
    은 더 이상 사용되지 않습니다
  • 문자열이 다른 값으로 시작하면 기수가 10 (10 진수)입니다

언급 한 다른 함수는 하나의 매개 변수 만 사용합니다

Number(object)

Number () 함수는 객체 인수를 객체의 값을 나타내는 숫자로 변환합니다.

값을 유효한 숫자로 변환 할 수 없으면 NaN이 반환됩니다.


parseInt (string) 은 문자열이 숫자로 시작하는 한 숫자가 아닌 문자를 포함하는 문자열을 숫자로 변환합니다.

'10px' => 10

문자열에 숫자가 아닌 문자가 포함 된 경우 숫자 (문자열) 는 NaN을 반환합니다.

'10px' => NaN

parseInt함수를 사용하면 입력 문자열에 기수를 지정할 수 있으며 정수 값으로 제한됩니다.

parseInt('Z', 36) === 35

Number함수로 호출 생성자는 문자열을 문법으로 구문 분석하며 10 진법과 16 진법으로 제한됩니다.

StringNumericLiteral :::
    StrWhiteSpace 선택  
    StrWhiteSpace 선택 StrNumericLiteral StrWhiteSpace 선택

StrWhiteSpace :::
    StrWhiteSpaceChar StrWhiteSpace 선택

StrWhiteSpaceChar :::
    공백 
    라인 터미네이터

StrNumericLiteral :::
    StrDecimalLiteral 
    HexIntegerLiteral

StrDecimalLiteral :::
    StrUnsignedDecimalLiteral 
    + StrUnsignedDecimalLiteral 
     - StrUnsignedDecimalLiteral

StrUnsignedDecimalLiteral :::
    무한대  
    DecimalDigits . DecimalDigits opt ExponentPart opt  
    . DecimalDigits ExponentPart opt      
    DecimalDigits ExponentPart opt

DecimalDigits :::
    10 진수 
    DecimalDigits DecimalDigits

DecimalDigit ::: 012 34 5678 9 중 하나
    

지수 부 :::
    지수 표시 자 부호있는 정수

ExponentIndicator ::: 전자 중 하나
    

SignedInteger :::
    10 진수 
    + DecimalDigits 
     - DecimalDigits

HexIntegerLiteral :::
    0x HexDigit 
     0X HexDigit
    HexIntegerLiteral HexDigit

HexDigit ::: 하나 
    0 1 2 3 4 5 6 7 8 9 ABCDEF ABCDEF

@sjngm의 답변에 대한 부록 :

둘 다 공백을 무시합니다.

var foo = "3"; console.log (parseInt (foo)); // 3 console.log (Number (foo)); // 삼

It is not exactly correct. As sjngm wrote parseInt parses string to first number. It is true. But the problem is when you want to parse number separated with whitespace ie. "12 345". In that case
parseInt("12 345") will return 12 instead of 12345. So to avoid that situation you must trim whitespaces before parsing to number. My solution would be:

     var number=parseInt("12 345".replace(/\s+/g, ''),10);

Notice one extra thing I used in parseInt() function. parseInt("string",10) will set the number to decimal format. If you would parse string like "08" you would get 0 because 8 is not a octal number.Explanation is here


Addendum to @sjngm's answer:

They both also ignore whitespace:

var foo = "    3     ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3

참고URL : https://stackoverflow.com/questions/4564158/what-is-the-difference-between-parseintstring-and-numberstring-in-javascript

반응형