근데 이게 좀 특이하게 동작하는 구석이 있다.
0으로 시작하는 문자열을 경우(0x 또는 0X로 시작하하지 않고) 브라우져는 8진수(IE,FF)또는 10진수(Opera)로 해석한다.
parseInt함수의 syntax는 다음과 같다.
parseInt(string[, radix])
- string: 정수로 바꿀 대상 문자열
- radix: 문자열을 바꿀때 사용할 기수(基數, base), 2이상 36이하인 정수 - optional
- returns: 문자열을 parsing한 정수값(10진수) 또는 NaN
그런데 ECMAScript 스펙을 보면 얘기가 좀 다르다.If the radix is not specified or is specified as 0, JavaScript assumes the following:
- If the input
stringbegins with "0x", the radix is 16 (hexadecimal).- If the input
stringbegins with "0", the radix is eight (octal). This feature is deprecated.- If the input
stringbegins with any other value, the radix is 10 (decimal).
radix가 없고 0으로 시작하는 문자열(but not 0x or 0X)을 8진수 또는 10진수로 구현하는것을 허용한다고 되어있다.
이렇다 보니 IE나 Firefox는 8진수로 반환을 하고 Opera의 경우에는 10진수로 반환을 한다.
이왕이면 그냥 10진수 하나로 정했으면 좋았을 것을..
스펙의 마지막 부분에 10진수로 반환하는것을 권장한다는 말이 있음에도 불구하고 브라우져들은 서로 다른 구현을 채택한듯 하다.
NOTE
parseInt may interpret only a leading portion of the string as an integer value; it ignores any
characters that cannot be interpreted as part of the notation of an integer, and no indication is given
that any such characters were ignored.
When radix is 0 or undefined and the string's number begins with a 0 digit not followed by an x or X,
then the implementation may, at its discretion, interpret the number either as being octal or as being
decimal. Implementations are encouraged to interpret numbers in this case as being decimal.
- ECMA-262 에서 발췌
사실 이것 때문에 07-08-07 이런거 파싱해서 달력을 만들어야 하는데 자꾸 다른 값이 나와서, widget만들면서 삽질좀 했다.
가능하면 parsetInt함수를 사용할 때에는 radix를 가능하면 명시하는 습관을 들이는 것이 좋을 듯하다.
더 자세한 내용은 아래 내용을 참조하자.
- MDC: Core JavaScript 1.5 Reference:Global Functions:parseInt
ECMA-262.pdfECMA-262 3rd Edition



댓글을 달아 주세요