常量
一句话解释
常量是 named 值那个, 一次设置, cannot 是更改虽然 program 运行.
用大白话说
constant 是like a variable with a lock on it。 You give it a name and a value once, and that value stays the same for the entire life of the program. If you try to reassign it, you get an error.
Constants are useful for values that should never change — mathematical constants like π, configuration values like a maximum number of retries, or fixed labels like a company name. Using a constant instead of a magic number makes your code easier to read and safer to maintain.
许多languages use a special keyword to declare constants: const in JavaScript, 最终 in Java, const in C. The naming convention often uses ALL_CAPS (e.g. MAX_RETRIES) so other developers instantly recognize the value is fixed.
示例
const PI = 3.14159;
console.log(PI); // 3.14159
PI = 3; // ❌ TypeError: Assignment to constant.PI 是常量. 一次设置到 3.14159, 任何 attempt 到 reassign 它 throws 错误.
常见混淆
容易混淆的对象: 变量
关键区别: 常量's 值是 fixed 之后 declaration and cannot 是 reassigned; 变量能 是更新 as 许多次数 as 需要.
相关术语
相关资源
相关课程
- 变量
变量 and constants 是 introduced together
相关项目
- 单元 Converter
Use constants for fixed conversion factors
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。