radix

强制在使用 parseInt() 时使用基数参数

💡 hasSuggestions

此规则报告的一些问题可通过编辑器 建议 手动修复

使用 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() 的行为,使其不再自动检测八进制字面,而是将它们视为十进制字面。但是,第一个参数的十六进制和十进制解释之间的差异导致许多开发者继续使用 radix 参数来确保以预期方式解释字符串。

¥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() 的第一个参数,因此此规则假定始终需要第二个参数(基数)。

¥Deprecated: String options "always" and "as-needed" are deprecated. Setting either of these options doesn’t change the behavior of this rule, which now always enforces providing a radix, as it was the case when the "always" option was specified. Since the default radix depends on the first argument of parseInt(), this rule assumes that the second argument (the radix) is always needed.

何时不使用

¥When Not To Use It

如果你希望在未指定基数参数时使用 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 中引入。

进阶读物

资源