手寫 parseInt

function parseInt(s, radix = 10) {
    // 不是string類型立刻NaN
    if (typeof s !== 'string') {
        return NaN;
    }
    // 進制必須爲2到36的數字
    if (typeof radix !== 'number' || radix < 2 || radix > 36) {
        return NaN;
    }
    // 結果初始值爲0
    let result = 0;
    // 循環字符串中的每一個字符轉爲 Unicode 編碼
    for (let i = 0; i < s.length; i += 1) {
        let c = s.charCodeAt(i);
        // 小寫大寫字母轉換爲數字
        if (c >= 97) {
            c -= 87;    // - 'a' + 10
        } else if (c >= 65) {
            c -= 55;    // - 'A' + 10
        } else {
            c -= 48;    // - '0'
        }
        // 如果字母轉化後的值大於進制數,則跳出循環返回之前的結果
        if (c >= radix) {
            if (i === 0) {
                return NaN;
            }
            break;
        }
        // 結果累加,和進制相關
        result = (result * radix) + c;
    }

    return result;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章