JavaScript 中的可选参数

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

Optional parameters in JavaScript

javascript

提问by Richard

Question

What is a good way of assigning a default value to an optional parameter?

为可选参数分配默认值的好方法是什么?

Background

背景

I'm playing around with optionalparameters in JavaScript, and the idea of assigning a default value if a parameter is not specified. My method in question accepts two parameters, the latter of which I deem to be optional, and if unspecified should default to false. My method looks something like this...

我正在使用JavaScript 中的可选参数,以及在未指定参数时分配默认值的想法。我所讨论的方法接受两个参数,我认为后者是可选的,如果未指定,则应默认为false. 我的方法看起来像这样......

// selects the item, appropriately updating any siblings
// item to select [, toggle on / off]
this.selectItem = function(item, toggle)
{
    toggle = toggle && typeof toggle === 'boolean';
    if (toggle)
    {
       // ...
    }
}

Testing

测试

After running a few tests on this jsFiddle, using the following principal for default value assigning:

此 jsFiddle上运行一些测试后,使用以下主体进行默认值分配:

function checkParamIsBoolean(param)
{
    param = param && typeof param === 'boolean';
}

checkParamIsBoolean('me'); // boolean
checkParamIsBoolean([]); // boolean
checkParamIsBoolean(true); // boolean
checkParamIsBoolean(false); // boolean
checkParamIsBoolean(1 == 1); // boolean
checkParamIsBoolean(1); // boolean
checkParamIsBoolean(null); // object
checkParamIsBoolean(undefined); // undefined
?

As you can, the results vary, and aren't desired.

尽你所能,结果会有所不同,而且是不希望的。

Expected

预期的

null= false
undefined= false

null= false
undefined=false

Actual

实际的

null= object
undefined= undefined

null= object
undefined=undefined

Summary

概括

Are there any alternative approaches to assigning a default value to an optional parameter if it's unspecified; would it be better to use _toggleas the parameter and then assign the value to var togglewithin the method?

如果未指定,是否有其他方法可以为可选参数分配默认值?将其_toggle用作参数然后var toggle在方法内分配值会更好吗?

采纳答案by Mariusz Jamro

Better solution is to use named arguments wraped in a object. It keeps your code clean and prevents errors in case of complex functions (with many default and non-default arguments). Otherwise you need to remember about the order of arguments and assign default values based on the types of arguments present (that's what you're trying to do).

更好的解决方案是使用包装在对象中的命名参数。它使您的代码保持干净并防止在复杂函数(具有许多默认和非默认参数)的情况下出错。否则,您需要记住参数的顺序并根据存在的参数类型分配默认值(这就是您要尝试执行的操作)。

That method is a primary way of passing params jQuery and jQuery's plugins.

该方法是传递参数jQuery 和 jQuery 插件的主要方式。

function test(options) { 

  // set up default options 
  var defaults = { 
    param1:      'test', 
    param2:      100
  }; 

  // combine options with default values
  var options = $.extend({}, defaults, options); // If you're not using jQuery you need different function here

  alert(options.param1)
  alert(options.param2)

}

test({'param2': 200}) // Call the function with just the second param

回答by sbgoran

You can use this construction for optional parameters in your code:

您可以将此构造用于代码中的可选参数:

//...
optionalParam = optionalParam || 'some default value';

In your concrete exaple it would be something like this:

在你的具体例子中,它会是这样的:

this.selectItem = function(item, toggle)
{
    toggle = toggle || false;
   // ...
}

But in your case you could use toogle (optional parameter) directly in if statement (since you only want to check for its existence. Or optionally you could enforce boolean value like this toogle = !!toogle(double negation).

但是在您的情况下,您可以直接在 if 语句中使用 toogle (可选参数)(因为您只想检查它是否存在。或者您可以选择强制执行这样的布尔值toogle = !!toogle(双重否定)。

回答by Simon Forsberg

A very simple way to check if toggle is undefined, and if it is then set a default value:

一种非常简单的方法来检查切换是否未定义,然后设置默认值:

if (toggle === undefined) toggle = "<your default value>";

if (toggle === undefined) toggle = "<your default value>";

Note that this does not change toggleif it is specified but of another type than what you expected.

请注意,toggle如果指定但不是您预期的类型,则这不会改变。

回答by floorish

Try it the other way around:

反过来试试:

param = typeof param === 'boolean' && param;

This will make sure all are a boolean, see this fiddle

这将确保所有都是布尔值,请参阅此小提琴

回答by Sepehr

Ifyou consider null(as well as no args passed), undefinedand ""(empty string) as "not an argument has passed to my function" use this statement:

如果您将null(以及没有传递参数)undefined""(空字符串)视为“没有参数已传递给我的函数”,请使用以下语句:

toggle = toggle&&toggle||default_value

Now if you pass null, undefinedor ""to your function as togglearg, this line fills it with default_value.

现在,如果您将null,undefined""作为togglearg传递给您的函数,该行将用default_value.

回答by Bergi

Why do you check the parameter to be boolean, if you expect an other result? The usual way would be checking for typeof toggle != "undefined", but in your case

如果您期望其他结果,为什么要检查参数为布尔值?通常的方法是检查typeof toggle != "undefined",但在你的情况下

toggle = Boolean(toggle);

should do the task. You can also use the shortcut !!toggle, or use it directly in the if-clause:

应该做任务。您也可以使用快捷方式!!toggle,或直接在 if 子句中使用它:

if (toggle) { // will evaluate to "false" for undefined
    ...

BTW, no need for a _toggleparameter; you can just reassign to toggle.

顺便说一句,不需要_toggle参数;你可以重新分配给toggle.

回答by Niclas Sahlin

You can replace

你可以更换

param = param && typeof param === 'boolean';

with

param = !!(param && typeof param === 'boolean');

This will convert the result of the statement to the boolean negate, and then negate it back again.

这会将语句的结果转换为布尔否定,然后再次否定它。

回答by Anthony

Take a look at jQuery extendand how they handle optional parameters.

看看jQuery 扩展以及它们如何处理可选参数。

回答by zVictor

It can easilly be done with ArgueJS:

它可以easilly可以用做ArgueJS

this.selectItem = function()
{
  arguments = __({item: undefined, toggle: [Boolean, false})
  if (arguments.toggle)
  {
     // ...
  }
}


You can also check the type of itemby changing undefinedby the desired type.

您还可以item通过更改undefined所需的类型来检查的类型。