语法错误:重新声明形式参数 "x"

当相同的变量名作为函数参数出现,然后再次在函数体中使用 let 赋值重新声明时,就会发生 JavaScript 异常 "形式参数的重新声明"。

¥The JavaScript exception "redeclaration of formal parameter" occurs when the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again.

信息

¥Message

SyntaxError: Identifier "x" has already been declared (V8-based)
SyntaxError: redeclaration of formal parameter "x" (Firefox)
SyntaxError: Cannot declare a let variable twice: 'x'. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

相同的变量名作为函数参数出现,然后再次在函数体中使用 let 赋值进行重新声明。JavaScript 中不允许使用 let 在同一函数或块作用域内重新声明同一变量。

¥The same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. Redeclaring the same variable within the same function or block scope using let is not allowed in JavaScript.

示例

¥Examples

重新声明的参数

¥Redeclared argument

在这种情况下,变量 "arg" 重新声明参数。

¥In this case, the variable "arg" redeclares the argument.

js
function f(arg) {
  let arg = "foo";
}

// SyntaxError: redeclaration of formal parameter "arg"

如果你想改变函数体中 "arg" 的值,你可以这样做,但不需要再次声明相同的变量。换句话说:你可以省略 let 关键字。如果你想创建一个新变量,你需要重命名它,因为它已经与函数参数冲突了。

¥If you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. In other words: you can omit the let keyword. If you want to create a new variable, you need to rename it as conflicts with the function parameter already.

js
function f(arg) {
  arg = "foo";
}

function g(arg) {
  let bar = "foo";
}

也可以看看

¥See also