类型错误:对 const "x" 的赋值无效
当尝试更改常量值时,会发生 JavaScript 异常 "对 const 的无效赋值"。JavaScript const
声明不能重新分配或重新声明。
¥The JavaScript exception "invalid assignment to const" occurs when it was attempted to
alter a constant value. JavaScript
const
declarations can't be re-assigned or redeclared.
信息
错误类型
什么地方出了错?
¥What went wrong?
常量是程序在正常执行期间无法更改的值。它不能通过重新分配来更改,也不能重新声明。在 JavaScript 中,常量是使用 const
关键字声明的。
¥A constant is a value that cannot be altered by the program during normal execution. It
cannot change through re-assignment, and it can't be redeclared. In JavaScript,
constants are declared using the
const
keyword.
示例
重新声明无效
修复错误
¥Fixing the error
有多种选项可以修复此错误。检查相关常量想要实现的目标。
¥There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.
改名
¥Rename
如果你打算声明另一个常量,请选择另一个名称并重新命名。该常量名称已在此范围内使用。
¥If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope.
const COLUMNS = 80;
const WIDE_COLUMNS = 120;
const、let 还是 var?
¥const, let or var?
如果你不想声明常量,请不要使用 const。也许你打算使用 let
声明块作用域变量或使用 var
声明全局变量。
¥Do not use const if you weren't meaning to declare a constant. Maybe you meant to
declare a block-scoped variable with
let
or
global variable with
var
.
let columns = 80;
// …
columns = 120;
范围界定
¥Scoping
检查你是否在正确的范围内。例如,这个常量应该出现在这个范围内还是应该出现在函数中?
¥Check if you are in the correct scope. Should this constant appear in this scope or was it meant to appear in a function, for example?
const COLUMNS = 80;
function setupBigScreenEnvironment() {
const COLUMNS = 120;
}
常量和不可变性
¥const and immutability
const
声明创建对值的只读引用。这并不意味着它所保存的值是不可变的,只是变量标识符不能被重新分配。例如,如果内容是对象,这意味着对象本身仍然可以更改。这意味着你无法更改存储在变量中的值:
¥The const
declaration creates a read-only reference to a value. It does
not mean the value it holds is immutable, just that the variable
identifier cannot be reassigned. For instance, in case the content is an object, this
means the object itself can still be altered. This means that you can't mutate the value
stored in a variable:
const obj = { foo: "bar" };
obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'
但是你可以改变变量中的属性:
¥But you can mutate the properties in a variable:
obj.foo = "baz";
obj; // { foo: "baz" }