语法错误:重复的形式参数 x

当函数创建两个或更多具有相同名称的参数 bindings,并且该函数不是只有简单参数的 non-strict 函数时,会发生 JavaScript 异常 "重复的形式参数 x" 或 "此上下文中不允许重复的参数名称"。

¥The JavaScript exception "duplicate formal argument x" or "duplicate argument names not allowed in this context" occurs when a function creates two or more parameter bindings with the same name, and the function is not a non-strict function with only simple parameters.

信息

¥Message

SyntaxError: Duplicate parameter name not allowed in this context (V8-based)
SyntaxError: duplicate formal argument x (Firefox)
SyntaxError: duplicate argument names not allowed in this context (Firefox)
SyntaxError: Cannot declare a parameter named 'x' in strict mode as it has already been declared. (Safari)
SyntaxError: Duplicate parameter 'x' not allowed in function with default parameter values. (Safari)
SyntaxError: Duplicate parameter 'x' not allowed in function with a rest parameter. (Safari)
SyntaxError: Duplicate parameter 'x' not allowed in function with destructuring parameters. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

有两个同名的形式参数很可能是一个错误 - 第二次出现会导致第一次出现无法通过参数名称访问。在旧版 JavaScript 中,这是允许的。因此,为了不破坏现有代码,这只有在保证代码不是遗留代码的情况下才会出错 - 因为它在 严格模式 中,或者它使用现代参数语法(restdefaultdestructured 参数)。

¥Having two formal parameters of the same name is likely a mistake—the second occurrence would cause the first occurrence to be inaccessible through the parameter name. In legacy JavaScript, this was allowed. Therefore, to not break existing code, this is only an error if the code is guaranteed to not be legacy—either because it is in strict mode or it uses modern parameter syntax (rest, default, or destructured parameters).

示例

¥Examples

无效案例

¥Invalid cases

js
"use strict";

function add(x, x) {
  // How can you access both "x" parameters?
  // SyntaxError: duplicate formal argument x
}
js
function doSomething(name, { name }) {
  // How can you access both "name" parameters?
  // SyntaxError: duplicate argument names not allowed in this context
}

有效案例

¥Valid cases

js
function doSomething(operationName, { name: userName }) {
  // You can access both "operationName" and "userName" parameters.
}

function doSomething(name, user) {
  // You can access both "name" and "user.name" parameters.
}

也可以看看

¥See also