1.首先我们要知道parseInt()可以接收一个字符串并且返回一个整数。
2.当只传递一个参数的时候:
• 如果 string 以 "0x" 开头,parseInt() 会把 string 的其余部分解析为十六进制的整数。
• 如果 string 以 0 开头,那么 ECMAScript v3 允许 parseInt() 的一个实现把其后的字符解析为八进制或十六进制的数字。
• 如果 string 以 1 ~ 9 的数字开头,parseInt() 将把它解析为十进制的整数。
3.函数的第二个参数可以定义接收的字符串代表的数字的进制。
4.提示:
• 只有字符串中的第一个数字会被返回。
• 开头和结尾的空格是允许的。
• 如果字符串的第一个字符不能被转换为数字,那么 parseInt() 会返回 NaN。
• 在字符串以"0"为开始时旧的浏览器默认使用八进制基数。ECMAScript 5,默认的是十进制的基数。
5.实例:
parseInt("10"); // 10
parseInt("10.33"); // 10
parseInt("10 20 30"); // 10
parseInt(" 10 "); // 10
parseInt("10 years"); // 10
parseInt("years 10"); // NaN
parseInt("10", 10); // 10
parseInt("010"); // 10
parseInt("10", 8); // 8
parseInt("0x10"); // 16
parseInt("10", 16); // 16
6.进制转换函数:
function baseConverter(value, fromBase, toBase) {
if (fromBase < 2 || fromBase > 36 || toBase < 2 || toBase > 36) {
throw new Error("进制范围必须在2到36之间");
}
function convertToDecimal(num, base) {
return parseInt(num, base);
}
function convertFromDecimal(num, base) {
return num.toString(base);
}
const decimalValue = convertToDecimal(value, fromBase);
return convertFromDecimal(decimalValue, toBase);
}
// 示例用法: console.log(baseConverter("1010", 2, 10)); // 输出 "10"
console.log(baseConverter("A", 16, 10)); // 输出 "10"
console.log(baseConverter("10", 10, 2)); // 输出 "1010"
console.log(baseConverter("10", 10, 16)); // 输出 "A"