SyntaxError: duplicate formal argument x
当一个函数创建两个或更多同名参数绑定,并且该函数不是一个仅包含简单参数的非严格函数时,JavaScript 会抛出异常“duplicate formal argument x”(重复的形式参数 x)或“duplicate argument names not allowed in this context”(在此上下文中不允许重复参数名)。
消息
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)
错误类型
SyntaxError
哪里出错了?
拥有两个同名形式参数很可能是一个错误——第二次出现将导致无法通过参数名访问第一次出现。在旧版 JavaScript 中,这是允许的。因此,为了不破坏现有代码,仅当代码保证不是旧版代码时(因为它处于严格模式下或使用了现代参数语法(剩余参数、默认参数或解构参数))才会抛出此错误。
示例
无效案例
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
}
有效情况
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.
}