javascript 检查函数中是否缺少参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12715157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:57:58  来源:igfitidea点击:

Checking for missing parameter in function

javascript

提问by 3coins

Is this the correct way to check for a missing parameter in a function? Would this work in all browsers? How about IE?

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

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

采纳答案by tkone

you can do:

你可以做:

name = name || 'default';

That says if nameis undefined or falsy (null, 0, "", false, {}, []), set it to "default".

这表示如果name未定义或虚假(null, 0, "", false, {}, []),请将其设置为"default"

js(h|l)int will complain about it, but it works at least as far as back as IE7. It's not invalid code at all or relying on some undocumented behavior either.

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

回答by zzzzBov

The way to check for parameters depends on what type of information you're passing to the function, and how you want your function to handle edge cases.

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

In most cases, you can use:

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

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

However, it might be an issue when you want to pass in falsey values (false, 0, NaN, '', undefined, null):

但是,当您想传入 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 wanted

Instead, you can check against undefined:

相反,您可以检查undefined

...
if (bar == undefined) {
    bar = 5
}
...

...however using the loose check allows both nulland undefinedto be overwritten (null == undefined):

...然而,使用松散检查允许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

So instead, a strict equality comparison (===) is generally preferred (null !== undefined):

因此,===通常更喜欢严格的相等比较 ( ) ( 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 introduced default parameters, which are essentially equivalent to strict checking against undefined:

ES2015 引入了默认参数,本质上等同于严格检查undefined

function foo(bar = 5) {
  console.log(bar)
}

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

This could lead to trouble if you need to know whether undefinedwas passed as a parameter.

如果您需要知道是否undefined作为参数传递,这可能会导致麻烦。

If you want to be absolutely certain that you're not passing up an argument that was provided, you can check the number of arguments passed to the function:

如果您想绝对确定您没有传递提供的参数,您可以检查传递给函数的参数数量:

...
if (arguments.length < 1) {
  bar = 5
}
...

Which means that you can successfully pass undefinedas an argument while also choosing to use a different default:

这意味着您可以成功地undefined作为参数传递,同时还可以选择使用不同的默认值:

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

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



If you have multiple parameters, you may want to use multiple defaults. I've recently found a use case for fallthrough on a switch statement, although the utility is questionable:

如果您有多个参数,您可能需要使用多个默认值。我最近在 switch 语句上发现了一个 fallthrough 用例,尽管该实用程序有问题

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

回答by Jon

The correct way to check is

正确的检查方法是

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

Of course callers can still "fool" you by calling getName(undefined), when a parameter has been provided but the check will flag it as not-provided nonetheless. But that's really a pathological scenario.

当然,调用者仍然可以通过调用来“愚弄”您getName(undefined),当提供了参数但检查仍会将其标记为未提供。但这确实是一个病态的场景。

回答by scrappedcola

Yes this would work in all browsers though if you want to see if it is defined you might use:

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

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