这两种检查参数的方式有什么区别?
function foo(a, b) {
this.a=a;
this.b=b;
}
使用:
if (arguments.length === 1) {}
或
if (this.b !== undefined) {}
最佳答案
如果你想检查强制参数,我将使用 arguments.length
作为第一步。如果你想检查可选参数,通常模式是:
function foo(a,b){
this.a = a || "foo";
// etc
}
请注意,这仅在参数不能为“虚假”值(例如,空字符串、零、空、未定义、假、NaN)时才有效。例如,如果您将一个空字符串作为 a
参数传递,您将得到 foo.如果您只想将 undefined
视为考虑参数可选的值,那么您必须执行以下操作:
function foo(a){
this.a = a === undefined ? "foo" : a;
// etc
}
如果您想同时考虑 null 和 undefined 以及可选参数,您可以:
function foo(a){
this.a = a == undefined ? "foo" : a;
// etc
}
当然也可以使用运算符typeof
。例如你希望 a
只能是一个字符串:
function foo(a) {
this.a = typeof a === "string" ? a : "";
// etc
}
您还可以强制 a
始终为字符串,在最坏的情况下将是给定的非字符串值(也未定义)的字符串版本:
function foo(a) {
this.a = String(a);
// etc
}
更复杂的情况有一些实用函数可以为您进行所有这些检查,您说的是必需的参数、可选的、默认值等。
关于javascript - 检查参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10297965/