Javascript:函数中的可选参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39140712/
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-08-23 22:15:40  来源:igfitidea点击:

Javascript : optional parameters in function

javascript

提问by vp_arth

Let's say I have this :

假设我有这个:

function concatenate(a, b, c) {
    // Concatenate a, b, and c
}

How do I handle those calls ?

我如何处理这些电话?

x = concatenate(a)

x = concatenate(a, b)

x = concatenate(a, c)

How can I make my function aware of the parameter I gave to it ?

我怎样才能让我的函数知道我给它的参数?

回答by Amadan

Any unfilled argument will be undefined.

任何未填写的参数将是undefined.

concatenate(a, c)is equivalent to concatenate(a, b). You cannot pass the third parameter without passing the second; but you can pass undefined(or null, I suppose) explicitly: concatenate(a, undefined, c).

concatenate(a, c)相当于concatenate(a, b)。你不能在不传递第二个参数的情况下传递第三个参数;但是你可以通过undefined(或者null,我想)明确:concatenate(a, undefined, c)

In the function, you can check for undefinedand replace with a default value.

在该函数中,您可以检查undefined并替换为默认值。

Alternately, you can use an object argument to imitate keyword arguments: concatenate({a: a, c: c}).

或者,您可以使用对象参数来模仿关键字参数:concatenate({a: a, c: c})

回答by vp_arth

Just use argumentsarray-like object:

只需使用arguments类似数组的对象:

function concatenate() {
  var result = '';
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}

回答by Andrej

from ES6/ES2015 on you can do similar as in php:

从 ES6/ES2015 开始,你可以像在 php 中那样做:

function concatenate(a, b = false, c = false) {
    // Concatenate a, b, and c
}

for the older versions, you can do:

对于旧版本,您可以执行以下操作:

function concatenate(a, b, c) {
   if( typeof b !== 'undefined' && typeof c !== 'undefined') {
    // code when a, b and c are defined
   } else if ( typeof b !== 'undefined' && typeof c == 'undefined') {
    // code when a and b are defined
   } else {
   // code
   }

}

I am sure there is a better approach too, but should work.

我相信也有更好的方法,但应该有效。

回答by Lewis

Use the ES6 rest parameterssyntax to get an array of arguments. Then simply joinits items to retrieve the concatenated string.

使用 ES6rest parameters语法获取参数数组。然后只需join它的项目来检索连接的字符串。

concatenate(a);
concatenate(a, b);
concatenate(a, c);

function concatenate(...args){
  // for old browsers
  // `...args` is an equivalent of `[].slice.call(arguments);`
  return args.join('');
}