radix
强制在使用 parseInt() 时使用基数参数
此规则报告的一些问题可通过编辑器 建议 手动修复
在使用 parseInt() 函数时,通常会省略第二个参数,即进制,让函数尝试从第一个参数判断它是什么类型的数字。默认情况下,parseInt() 会自动检测十进制和十六进制(通过 0x 前缀)。在 ECMAScript 5 之前,parseInt() 也会自动检测八进制字面量,这会引发问题,因为许多开发者认为前导的 0 会被忽略。
🌐 When using the parseInt() function it is common to omit the second argument, the radix, and let the function try to determine from the first argument what type of number it is. By default, parseInt() will autodetect decimal and hexadecimal (via 0x prefix). Prior to ECMAScript 5, parseInt() also autodetected octal literals, which caused problems because many developers assumed a leading 0 would be ignored.
这种混淆导致有人建议你总是使用 parseInt() 的 radix 参数以消除意外后果。所以不要这样做:
🌐 This confusion led to the suggestion that you always use the radix parameter to parseInt() to eliminate unintended consequences. So instead of doing this:
const num = parseInt("071"); // 57
做这个:
🌐 Do this:
const num = parseInt("071", 10); // 71
ECMAScript 5 改变了 parseInt() 的行为,使其不再自动检测八进制字面量,而是将其视为十进制字面量。然而,第一个参数的十六进制和十进制解释之间的差异导致许多开发者仍然使用基数参数,以确保字符串按预期方式解释。
🌐 ECMAScript 5 changed the behavior of parseInt() so that it no longer autodetects octal literals and instead treats them as decimal literals. However, the differences between hexadecimal and decimal interpretation of the first parameter causes many developers to continue using the radix parameter to ensure the string is interpreted in the intended way.
规则详情
🌐 Rule Details
此规则旨在防止将字符串意外转换为与预期基数不同的数字。
🌐 This rule is aimed at preventing the unintended conversion of a string to a number of a different base than intended.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint radix: "error"*/
const num = parseInt("071");
const num1 = parseInt(someValue);
const num2 = parseInt("071", "abc");
const num3 = parseInt("071", 37);
const num4 = parseInt();
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint radix: "error"*/
const num = parseInt("071", 10);
const num1 = parseInt("071", 8);
const num2 = parseFloat(someValue);
选项
🌐 Options
已弃用: 字符串选项 "always" 和 "as-needed" 已被弃用。设置其中任一选项不会改变此规则的行为,该规则现在始终强制提供基数,就像指定 "always" 选项时的情况一样。由于默认基数取决于 parseInt() 的第一个参数,因此此规则假设始终需要第二个参数(基数)。
何时不使用
🌐 When Not To Use It
如果你想在未指定 radix 参数时使用 parseInt() 函数的默认行为,你可以关闭此规则。
🌐 If you want to use the default behavior of the parseInt() function when the radix argument is not specified, you can turn this rule off.
版本
此规则是在 ESLint v0.0.7 中引入。