这两种检查参数的方法有什么区别?
function foo(a, b) {
this.a=a;
this.b=b;
}
使用:
if (arguments.length === 1) {}
或者
if (this.b !== undefined) {}
这两种检查参数的方法有什么区别?
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
}
请注意,这仅在参数不能是“假”值(因此,空字符串、零、null、未定义、假、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
}
更复杂的情况有一些实用功能可以为您完成所有这些检查,您可以在其中说出所需的参数、可选参数、默认值等。
Check in what terms? Can the function proceed with a default value/bahavior, or should it stop if something was missed?
Commonly you an default the behavior, but that depends on the purpose/use of the function:
function foo(a,b){
a = a || {};
b = b || 5;
// continue
}
If you're looking for something absent, you can check undefined
and halt:
function foo(a){
if (a === undefined){
return false;
}
}
In short, it's entirely up to you and how you want a function to proceed given an absent or incorrectly assigned variable. Another for instance:
function bar(b){
if (typeof b !== 'function'){
b = function(){};
}
// continue on...
}
b!==undefined
很可能是你想要的
如果您执行 foo() 或 f(1,2,3),第一个将失败