这是检查函数中缺少参数的正确方法吗?这适用于所有浏览器吗?IE怎么样?
function getName(name){
name = name != null ? name : "default";
return name;
}
Run Code Online (Sandbox Code Playgroud)
zzz*_*Bov 55
检查参数的方法取决于您传递给函数的信息类型,以及您希望函数处理边缘情况的方式.
在大多数情况下,您可以使用:
...
bar = bar || ...default value here...
...
Run Code Online (Sandbox Code Playgroud)
但是,如果你想在falsey值传递给它可能是一个问题(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 wantedRun Code Online (Sandbox Code Playgroud)
相反,您可以检查undefined:
...
if (bar == undefined) {
bar = 5
}
...
Run Code Online (Sandbox Code Playgroud)
... ...但是使用松散检查同时允许null和undefined被覆盖(null == undefined):
function foo(bar) {
if (bar == undefined) {
bar = 5
}
console.log(bar)
}
foo() // 5
foo(undefined) // 5
foo(null) // 5
foo(1) // 1Run Code Online (Sandbox Code Playgroud)
因此,===通常首选(null !== undefined)一个严格的相等比较():
function foo(bar) {
if (bar === undefined) {
bar = 5
}
console.log(bar)
}
foo() // 5
foo(undefined) // 5
foo(null) // null
foo(1) // 1Run Code Online (Sandbox Code Playgroud)
ES2015引入了默认参数,这些参数基本上等同于严格检查undefined:
function foo(bar = 5) {
console.log(bar)
}
foo() // 5
foo(undefined) // 5
foo(null) // null
foo(1) // 1Run Code Online (Sandbox Code Playgroud)
如果您需要知道是否undefined作为参数传递,这可能会导致问题.
如果你想绝对确定你没有传递一个提供的参数,你可以检查传递给函数的参数数量:
...
if (arguments.length < 1) {
bar = 5
}
...
Run Code Online (Sandbox Code Playgroud)
这意味着您可以成功传递undefined作为参数,同时还选择使用不同的默认值:
function foo(bar) {
if (arguments.length < 1) {
bar = 5
}
console.log(bar)
}
foo() // 5
foo(undefined) // undefined
foo(null) // null
foo(1) // 1Run Code Online (Sandbox Code Playgroud)
如果您有多个参数,则可能需要使用多个默认值.我最近在switch语句中找到了一个用例,尽管该实用程序值得怀疑:
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 40Run Code Online (Sandbox Code Playgroud)
tko*_*one 18
你可以做:
name = name || 'default';
Run Code Online (Sandbox Code Playgroud)
这表示,如果name未定义或falsy( ,null,0,"",false,{}),[]将其设置为"default".
js(h | l)int会抱怨它,但它至少可以像IE7一样工作.它根本不是无效代码,也不依赖于某些未记录的行为.
正确的检查方法是
if (typeof name === "undefined") {
// ...
}
Run Code Online (Sandbox Code Playgroud)
当然getName(undefined),当提供参数时,调用者仍然可以通过调用来"欺骗"你,但是检查会将其标记为未提供参数.但这确实是一种病态情景.
| 归档时间: |
|
| 查看次数: |
15970 次 |
| 最近记录: |