语法错误:缺少形式参数
当你的函数声明缺少有效参数时,就会出现 JavaScript 异常 "缺少形式参数"。
¥The JavaScript exception "missing formal parameter" occurs when your function declaration is missing valid parameters.
信息
错误类型
什么地方出了错?
¥What went wrong?
"形式参数" 是 "功能参数" 的一种奇特说法。你的函数声明缺少有效参数。在函数的声明中,参数必须是 identifiers,而不是数字、字符串或对象等任何值。声明函数和调用函数是两个独立的步骤。声明需要标识符作为参数,并且仅在调用(调用)函数时,你才提供函数应使用的值。
¥"Formal parameter" is a fancy way of saying "function parameter". Your function declaration is missing valid parameters. In the declaration of a function, the parameters must be identifiers, not any value like numbers, strings, or objects. Declaring functions and calling functions are two separate steps. Declarations require identifier as parameters, and only when calling (invoking) the function, you provide the values the function should use.
在 JavaScript 中,标识符只能包含字母数字字符(或 "$" 或 "_"),并且不能以数字开头。标识符与字符串的不同之处在于,字符串是数据,而标识符是代码的一部分。
¥In JavaScript, identifiers can contain only alphanumeric characters (or "$" or "_"), and may not start with a digit. An identifier differs from a string in that a string is data, while an identifier is part of the code.
示例
提供适当的功能参数
¥Provide proper function parameters
设置函数时,函数参数必须是标识符。所有这些函数声明都会失败,因为它们为其参数提供值:
¥Function parameters must be identifiers when setting up a function. All these function declarations fail, as they are providing values for their parameters:
function square(3) {
return number * number;
}
// SyntaxError: missing formal parameter
function greet("Howdy") {
return greeting;
}
// SyntaxError: missing formal parameter
function log({ obj: "value"}) {
console.log(arg)
}
// SyntaxError: missing formal parameter
你需要在函数声明中使用标识符:
¥You will need to use identifiers in function declarations:
function square(number) {
return number * number;
}
function greet(greeting) {
return greeting;
}
function log(arg) {
console.log(arg);
}
然后,你可以使用你喜欢的参数调用这些函数:
¥You can then call these functions with the arguments you like:
square(2); // 4
greet("Howdy"); // "Howdy"
log({ obj: "value" }); // { obj: "value" }
也可以看看
¥See also