javascript 在函数中设置默认变量值

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

Setting a default variable value in a function

javascriptjquery

提问by Karl-André Gagnon

I am doing a lot of front-end developement and I see myself doing this a lot :

我正在做很多前端开发,我看到自己做了很多:

function doSomething(arg){
    var int = arg ? arg : 400
    //some code after
}

So I was wondering if the was a way to do this, but shorter and cleaner (I don't like to see argtwice in the same line).

所以我想知道这是否是一种方法,但更短更干净(我不喜欢arg在同一行看到两次)。

I've seen some people doing something like that :

我见过一些人做这样的事情:

var int = arg || 400;

And since I don't know in wich order I needed to place the value, I tried arg || 400and 400 || arg, but it will always set intto the value at the right, even if argis undefined.

因为我不知道我需要按什么顺序放置值,所以我尝试了arg || 400400 || arg,但它总是会设置int为右侧的值,即使arg未定义。

I know in PHP you can do something like function doSomething(arg = 400)to set a default value and in a jQuery plugin you can use .extend()to have default property, but is there a short way with a single variable? Or do i have to keep using my way?

我知道在 PHP 中你可以做一些类似function doSomething(arg = 400)设置默认值的事情,在一个 jQuery 插件中你可以使用.extend()默认属性,但是有一个简单的方法吗?还是我必须继续使用我的方式?

Thank for any help and if you can give me ressources, it would be appreciated.

感谢您的帮助,如果您能给我资源,将不胜感激。

回答by Denys Séguret

There's really no shorter clean way than

真的没有比这更短的清洁方式了

var int = arg || 400;

In fact, the correct way would be longer, if you want to allow arg to be passed as 0, falseor "":

事实上,正确的方法会更长,如果你想让 arg 作为0false或者""

var int = arg===undefined ? 400 : arg;

A slight and frequent improvement is to not declare a new variable but use the original one:

一个轻微而频繁的改进是不声明一个新变量而是使用原始变量:

if (arg===undefined) arg=400;

回答by Haben

function func(x,y){
   if(typeof(x)==='undefined') x = 10;
   if(typeof(y)==='undefined') y = 20;

   //code goes here
}

回答by Werzi2001

The problem with your solutions is that a value that evaluates to false (for example "false" or "0") also trigger the default value. So for every parameter that could possibly ever have a value that evaluates to false you have to check for "undefined" explicitly.

您的解决方案的问题是评估为假的值(例如“假”或“0”)也会触发默认值。因此,对于每个可能具有评估为 false 的值的参数,您必须明确检查“未定义”。

var int = (typeof x === 'undefined') ? default : x

If this is not possible you can use

如果这是不可能的,你可以使用

var int = x ? x : default
OR
var int = x || default

Another option would be to use the arguments array and check if the parameters were given. But this can only be used if your optional parameters are the last ones.

另一种选择是使用参数数组并检查是否给出了参数。但这只能在您的可选参数是最后一个时使用。

function test(x, y) {
    var int1 = (arguments.length > 0) ? x : default;
    var int2 = (arguments.length > 1) ? y : default;
}

回答by HBP

Not directly related to the question, but why create a new variable to mirror an argument?

与问题没有直接关系,但为什么要创建一个新变量来反映参数?

In this situation I would use :

在这种情况下,我会使用:

!arg && (arg = 400);

However, this tests argfor falsity which means that the values false, 0, '', nulland undefinedwould all cause argto be set to 400. If this is not the desired result, perhaps a value of 0is a valid argvalue then I usually test argument.length:

但是,这种测试arg为假,这意味着价值false0''null并且undefined将所有原因arg被设置为400。如果这不是想要的结果,也许值0是一个有效值,arg那么我通常测试argument.length

function f (arg) {
  !arguments.length && (arg = 400);

This checks if anyvalue was passed and sets argonly in the case that the call specified no arguments at all.

这会检查是否传递了任何值,并且arg仅在调用完全没有指定参数的情况下进行设置。

Only is specific instances where 0is not a desired value would I use the construct

只有在特定情况下,0我才会使用该构造

 arg || 400

which again suffers from the falsity test

再次受到错误测试的影响

If it is important that argbe numeric you could use :

如果重要的arg是数字,您可以使用:

 typeof arg !== 'number' && (arg = 400);

which would ensure that argwas a number and in the rest of the code.

这将确保这arg是一个数字,并且在代码的其余部分中。

In conclusion: it depends on exactly how you want to use the argument, what values are valid and how much you trust the callers of your code.

总而言之:这取决于您想要如何使用参数、哪些值是有效的以及您对代码调用者的信任程度。

回答by andlrc

I would check arguments.length:

我会检查arguments.length

var f = function(arg) {
  var myArg = arguments.length > 0 ? arg : 400;
};

回答by Karl-André Gagnon

In ES6, you can set default value to arguments the same way we do in PHP :

在 ES6 中,您可以像在 PHP 中一样为参数设置默认值:

function foo( a = [], b = 'string', c = false ){}

Default value can also be set to a previous argument ou even a function's return value

默认值也可以设置为前一个参数,甚至是函数的返回值

function foo( a = true, b = a, c = bar() ){}

This will also work with ES6 compilers. The end result will look like this

这也适用于 ES6 编译器。最终结果将如下所示

function foo() {
  var a = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
  var b = arguments.length <= 1 || arguments[1] === undefined ? a : arguments[1];
  var c = arguments.length <= 2 || arguments[2] === undefined ? bar() : arguments[2];
}