检查参数的方法取决于您传递给函数的信息类型以及您希望函数如何处理边缘情况。
大多数情况下,您可以使用:
...
bar = bar || ...default value here...
...
但是,当您想传递错误值时,这可能是一个问题(false
, 0
, NaN
, ''
, undefined
, null
):
function foo(bar) {
bar = bar || 5
console.log(bar)
}
foo() // 5
foo(undefined) // 5
foo(null) // 5
foo(1) // 1
foo(0) // 5, probably not what you wanted
相反,您可以检查undefined
:
...
if (bar == undefined) {
bar = 5
}
...
...但是使用松散支票可以同时允许null
and undefined
被覆盖(null == undefined
):
function foo(bar) {
if (bar == undefined) {
bar = 5
}
console.log(bar)
}
foo() // 5
foo(undefined) // 5
foo(null) // 5
foo(1) // 1
因此,严格的相等比较(===
) 通常优选 (null !== undefined
):
function foo(bar) {
if (bar === undefined) {
bar = 5
}
console.log(bar)
}
foo() // 5
foo(undefined) // 5
foo(null) // null
foo(1) // 1
ES2015介绍默认参数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters,这本质上相当于严格检查undefined
:
function foo(bar = 5) {
console.log(bar)
}
foo() // 5
foo(undefined) // 5
foo(null) // null
foo(1) // 1
如果您需要知道是否undefined
作为参数传递。
如果您想绝对确定没有传递所提供的参数,您可以检查传递给函数的参数数量:
...
if (arguments.length < 1) {
bar = 5
}
...
这意味着你可以顺利通过undefined
作为参数,同时还选择使用不同的默认值:
function foo(bar) {
if (arguments.length < 1) {
bar = 5
}
console.log(bar)
}
foo() // 5
foo(undefined) // undefined
foo(null) // null
foo(1) // 1
如果您有多个参数,您可能需要使用多个默认值。我最近发现了一个 switch 语句失败的用例,尽管实用性值得怀疑 https://stackoverflow.com/questions/12537937/implicit-fall-through-code-smell-or-elegant-design:
function foo(bar, baz, fizz, buzz) {
switch (arguments.length) {
case 0:
bar = 1;
//continue; might as well point out that implicit fall-through is desired
case 1:
baz = 2;
//continue;
case 2:
fizz = 3;
//continue;
case 3:
buzz = 4;
//continue;
}
console.log(bar, baz, fizz, buzz)
}
foo() // 1 2 3 4
foo(10) // 10 2 3 4
foo(10, 20) // 10 20 3 4
foo(10, 20, 30) // 10 20 30 4
foo(10, 20, 30, 40) // 10 20 30 40