检查功能中是否缺少参数

时间:2012-10-03 19:07:23

标签: javascript

这是检查函数中缺少参数的正确方法吗?这适用于所有浏览器吗? IE怎么样?

function getName(name){
    name = name != null ? name : "default";
    return name;
}

4 个答案:

答案 0 :(得分:53)

检查参数的方法取决于您传递给函数的信息类型,以及您希望函数处理边缘情况的方式。

在大多数情况下,您可以使用:

...
bar = bar || ...default value here...
...

但是,当您想要传递虚假值(false0NaN''undefined,{时,可能会出现问题。 {1}}):

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 } ... nullundefined):

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

ES2015引入了default parameters,这基本上等同于对function foo(bar) { if (bar === undefined) { bar = 5 } console.log(bar) } foo() // 5 foo(undefined) // 5 foo(null) // null foo(1) // 1进行严格检查:

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


如果您有多个参数,则可能需要使用多个默认值。我最近在switch语句中发现了一个用例,尽管the utility is questionable

function foo(bar) {
  if (arguments.length < 1) {
    bar = 5
  }
  console.log(bar)
}

foo()          // 5
foo(undefined) // undefined
foo(null)      // null
foo(1)         // 1

答案 1 :(得分:17)

你可以这样做:

name = name || 'default';

如果name未定义或假(null0""false{},{{1} }),将其设置为[]

js(h | l)int会抱怨它,但它至少可以像IE7一样工作。它根本不是无效代码,也不依赖于某些未记录的行为。

答案 2 :(得分:7)

正确的检查方法是

if (typeof name === "undefined") {
    // ...
}

当然,当提供参数时,呼叫者仍然可以通过调用getName(undefined)来“愚弄”你,但检查会将其标记为未提供参数。但这确实是一种病态情景。

答案 3 :(得分:0)

是的,这适用于所有浏览器,但如果您想查看它是否已定义,您可以使用:

function getName(name){
   name = typeof(name) !== "undefined" ? name : "default";
   return name;
}