js 实现parseint

实现 parseInt 的功能
JavaScript 的 parseInt 函数用于将字符串转换为整数。以下是手动实现 parseInt 功能的几种方法:
方法一:基础实现
function customParseInt(str, radix = 10) {
if (typeof str !== 'string' && typeof str !== 'number') {
return NaN;
}
str = String(str).trim();
if (!str.length) return NaN;
radix = radix || 10;
if (radix < 2 || radix > 36) return NaN;
let sign = 1;
let index = 0;
if (str[0] === '-') {
sign = -1;
index++;
} else if (str[0] === '+') {
index++;
}
let result = 0;
const digits = '0123456789abcdefghijklmnopqrstuvwxyz';
const lowerStr = str.toLowerCase();
while (index < lowerStr.length) {
const char = lowerStr[index];
const digit = digits.indexOf(char);
if (digit === -1 || digit >= radix) break;
result = result * radix + digit;
index++;
}
return sign * result;
}
方法二:简化版(仅支持十进制)
function simpleParseInt(str) {
const num = Number(str);
return isNaN(num) ? NaN : Math.trunc(num);
}
方法三:使用正则表达式
function regexParseInt(str, radix = 10) {
if (typeof str !== 'string' && typeof str !== 'number') return NaN;
str = String(str).trim();
if (!str.length) return NaN;
const regex = /^[+-]?(\d+)/;
const match = str.match(regex);
if (!match) return NaN;
return parseInt(match[0], radix);
}
注意事项
- 进制范围:
radix必须在 2 到 36 之间,否则返回NaN。 - 符号处理:字符串可以以
+或-开头,表示正负数。 - 非数字字符:遇到非数字字符时停止解析。
- 空白字符:字符串前后的空白字符会被忽略。
测试用例
console.log(customParseInt('123')); // 123
console.log(customParseInt('12.3')); // 12
console.log(customParseInt('0xF', 16)); // 15
console.log(customParseInt('hello')); // NaN
通过以上方法可以实现类似 parseInt 的功能,具体选择哪种方法取决于需求场景。







