noMagicNumbers
¥Summary
-
规则生效日期:
v2.1.0¥Rule available since:
v2.1.0 -
诊断类别:
lint/style/noMagicNumbers¥Diagnostic Category:
lint/style/noMagicNumbers -
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 information。
¥The default severity of this rule is information.
-
来源:
¥Sources:
¥How to configure
{ "linter": { "rules": { "style": { "noMagicNumbers": "error" } } }}¥Description
报告 “魔数” 的使用情况 - 直接使用数字,而不是将其赋值给命名常量。
¥Reports usage of “magic numbers” — numbers used directly instead of being assigned to named constants.
其目标是通过鼓励开发者将此类数字提取到命名常量中,并明确其用途,从而提高代码的可维护性和可读性。
¥Its goal is to improve code maintainability and readability by encouraging developers to extract such numbers into named constants, making their purpose explicit.
忽略:
¥It ignores:
-
任何位置出现的非魔法值(例如 0、1、2、10、24、60 及其负数或 bigint 形式),包括算术表达式、函数调用等。
¥non-magic values (like 0, 1, 2, 10, 24, 60, and their negative or bigint forms) found anywhere, including arithmetic expressions, fn calls etc.
-
数组索引
¥Array indices
-
枚举值
¥Enum values
-
变量或类属性声明中的初始值
¥Initial values in variable or class property declarations
-
函数参数或解构模式中的默认值
¥Default values in function parameters or destructuring patterns
-
JSON.stringify 和 parseInt 的参数(例如,
JSON.stringify(22)、parseInt("123", 8))¥Arguments to JSON.stringify and parseInt (e.g.,
JSON.stringify(22),parseInt("123", 8)) -
位运算中的操作数(例如,
a & 7、a | 7)¥Operands in bitwise operations (e.g.,
a & 7,a | 7) -
JSX 表达式中的值(例如,
<div>{1}</div>)¥Values in JSX expressions (e.g.,
<div>{1}</div>) -
对象属性值(例如,
{ tax: 0.25 })¥Object property values (e.g.,
{ tax: 0.25 })
¥Examples
¥Invalid
let total = price * 1.23; // Magic number for tax ratecode-block.js:1:21 lint/style/noMagicNumbers ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Magic number detected. Extract it to a constant with a meaningful name.
> 1 │ let total = price * 1.23; // Magic number for tax rate
│ ^^^^
2 │
ℹ Code is more readable and refactoring easier when special numbers are declared as constants as it makes their meaning explicit.
¥Valid
const TAX_RATE = 1.23;let total = price * TAX_RATE;const TAX_RATE = 1.23 as const;let total = price * TAX_RATE;¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号