Table of Contents
parseInt(string, radix)
根据提供的精度 radix 将第一个参数转换成数值型。
开头的空格会被忽略掉。
radix 的值
| 值 | 描述 |
|---|---|
| undefined 或 0 | radix 会被当做 10 来处理,除了 0x or 0X 开头的字符串(这类会被当做16进制处理) |
| 16 | 需要字符串以 0x 或 0X 开头 |
函数处理过程:
将第一个参数字符串化
inputString = ToString(string)- 类型为
Object情况处理
primValue = ToPrimitive(input argument, hint String)- 返回
ToString(primValue)值
- 类型为
去开头的空字符(前导空格),
S = trimStart(inputString)初始化符号位
sign = 1如果
S不为空切第一个字符是负号-,sign = -1如果
S不为空切第一个字符是+或-,就移除第一个字符将精度参数值转成 32 位整型
R = ToInt32(radix)设置
stripPrefix = true如果
R ≠ 0就执行:如果精度值超出范围(
R < 2 or R > 36) ,直接返回NaN如果
R ≠ 16设置stripPrefix = false
如果
R = 0则R = 10如果
stripPrefix = true- 如果
S大于 2,并且前两个字符是0x或0X,然后就将前两个字符从S
去掉,并设置R = 16
- 如果
如果
S包含了任意非精度数字,设置Z值为第一个这样的字符之前的所有字符组
成的子串,否则Z = S如果
Z是空的,返回NaN设置
mathInt值为Z进制字符串代表的数字(比如:八进制Z = 0.., 那么
mathInt = 8). 使用A-Z, a-z代表10 ~ 35
伪码
function myParseInt(string, radix) {
// 1. convert `string` to string
let intputString = '' + string
// 2. trim whitespace char
let S = inputString.trim()
// 3. init sign value
let sign = -1
// 4. set sign value by the first char of string
sign = S[0] === '-' ? -1 : sign
const firstChar = S[0]
// 5. to remove the sign char of first char
if (firstChar === '-' || firstChar === '+') {
S = S.substr(1)
}
// 6. convert the radix to int and save it
const R = +radix
// 7. init stripPrefix value(indicate if S has radix char)
let stripPrefix = true
// 8. judge the radix value
if (R !== 0) {
if (R < 2 || R > 36) {
// 7.1 beyond the radix range
return NaN
} else if (R !== 16) {
// 7.2 the 16radix value need to strip the prefix(as. 0x or 0X)
// and other radix dont need to strip prefix
stripPrefix = false
}
} else {
// set to 10 radix if input radix = 0
R = 10
}
// 10. if need to strip prefix
if (stripPrefix) {
// 10.1 if len of S >= 2
if (S.length >= 2) {
const firstTwoChars = S.substr(0, 2)
if (firstTwoChars === '0x' || firstTwoChars === '0X') {
S = S.substr(2)
R = 16
}
}
}
// 11.
}
图解


本文详细介绍了 JavaScript 中的 parseInt 函数工作原理,包括如何根据指定基数转换字符串为整数,处理字符串前导空格及不同基数的特殊情况。
805

被折叠的 条评论
为什么被折叠?



