JavaScript實現parseInt()

當參數 radix 的值爲 0,或沒有設置該參數時,parseInt() 會根據 string 來判斷數字的基數。git

舉例,若是 string 以 "0x" 開頭,parseInt() 會把 string 的其他部分解析爲十六進制的整數。若是 string 以 0 開頭,那麼 ECMAScript v3 容許 parseInt() 的一個實現把其後的字符解析爲八進制或十六進制的數字。若是 string 以 1 ~ 9 的數字開頭,parseInt() 將把它解析爲十進制的整數。函數

只有字符串中的第一個數字會被返回。測試

開頭和結尾的空格是容許的。code

function _parseInt (string, radix) {
    if (typeof string !== "string" && typeof string !== "number") return NaN;
    if (radix && (typeof radix !== "number" || /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/.test(radix) || radix > 36 || radix < 2)) return NaN;
    string = String(string)
    var rexp = (radix == 10) ? /(-?)([0]?)([0-9]+)/ : /(-?)([0]?[Xx]?)([0-9a-fA-F]+)/,
        a = string.match(rexp),
        sign = a[1],
        rawRadix = a[2],
        rawNum = a[3],
        result = 0,
        strArr = rawNum.split(''),
        len = strArr.length,
        numArr = [];
    if (a && !radix) {
        if ( rawRadix.toUpperCase() === "0X") {
            radix = 16;
        } else if (rawRadix === "0") {
            radix = 8;
        } else {
            radix = 10;
        }
    }
    for (var i = 0; i < len; i++){
        var num;
        var charCode = strArr[i].toUpperCase().charCodeAt(0);
        if(radix <=36 && radix >= 11) {
            if (charCode >= 65 && charCode <= 90) {
                num = charCode - 55;
            } else {
                num = charCode - 48;
            }
        }  else {
            num = charCode - 48;
        }
        if (num < radix) {
            numArr.push(num);
        } else {
            return NaN
        };
    }
    if(numArr.length > 0) {
      numArr.forEach(function(item, j){
          result += item * Math.pow(radix, numArr.length-j-1);
      })
    }
    if(sign === "-"){
      result = -result;
    }
    return result
}

來自MDN關於parseInt()裏面的測試用例ip

// 如下例子均返回15:
console.log(_parseInt("F", 16));
console.log(_parseInt("17", 8));
console.log(_parseInt("15", 10));
console.log(_parseInt(15.99, 10));
console.log(_parseInt("FXX123", 16));
console.log(_parseInt("1111", 2));
console.log(_parseInt("15*3", 10));
console.log(_parseInt("12", 13));

// 如下例子均返回 NaN:
console.log(_parseInt("Hello", 8)); // Not a number at all
console.log(_parseInt("546", 2));   // Digits are not valid for binary representations

// 如下例子均返回 -15:
console.log(_parseInt("-F", 16));
console.log(_parseInt("-0F", 16));
console.log(_parseInt("-0XF", 16));
console.log(_parseInt(-15.1, 10));
console.log(_parseInt(" -17", 8));
console.log(_parseInt(" -15", 10));
console.log(_parseInt("-1111", 2));
console.log(_parseInt("-15e1", 10));
console.log(_parseInt("-12", 13));
// 下例中也所有返回 17,由於輸入的 string 參數以 "0x" 開頭時做爲十六進制數字解釋,而第二個參數假如通過 Number 函數轉換後爲 0 或 NaN,則將會忽略。
console.log(_parseInt("0x11", 16));
console.log(_parseInt("0x11", 0));
console.log(_parseInt("0x11"));

// 下面的例子返回 224
console.log(_parseInt("0e0",16));
相關文章
相關標籤/搜索