code_prettify

2016年10月12日 星期三

javascript parseInt(string, radix),忘了 radix就會有些怪怪的 bug

公司有個功能需要 user輸入月份,長度強制兩位數,所以是 01, 02.....12

UI很簡單的用 parseInt(string)檢查輸入月份是否為介於 1-12之間的數字, server side會 format user input

功能一直沒問題,直到 8月開始... user送不出表單,頁面一直跳請輸入 1 ~ 12之間的數字

因為 0開頭的字串,parseInt視為 8進位 parse

"If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated

If the string begins with any other value, the radix is 10 (decimal)"
.....摘自 W3Schools

意思是
0x開頭的字串,視為 16進位
0開頭的字串,視為 8進位(已棄用)--棄用歸棄用,user的 browser又不見得永遠是最新的
其他的都視為 10進位

01 - 07都是合法的 8進位,但是 08以 8進位來說不是正確的數字, parseInt return 0, bug於焉而生

加上 radix 10就 OK了