有没有更好的方法在JavaScript中执行可选的函数参数? [重复]

本文翻译自:Is there a better way to do optional function parameters in JavaScript? [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

I've always handled optional parameters in JavaScript like this: 我总是在JavaScript中处理可选参数,如下所示:

function myFunc(requiredArg, optionalArg){
  optionalArg = optionalArg || 'defaultValue';

  // Do stuff
}

Is there a better way to do it? 有没有更好的方法呢?

Are there any cases where using || 有没有使用|| like that is going to fail? 那会失败吗?


#1楼

参考:https://stackoom.com/question/cjd/有没有更好的方法在JavaScript中执行可选的函数参数-重复


#2楼

If you're using defaults extensively, this seems much more readable: 如果你广泛使用默认值,这似乎更具可读性:

function usageExemple(a,b,c,d){
    //defaults
    a=defaultValue(a,1);
    b=defaultValue(b,2);
    c=defaultValue(c,4);
    d=defaultValue(d,8);

    var x = a+b+c+d;
    return x;
}

Just declare this function on the global escope. 只需在全局escope上声明此函数即可。

function defaultValue(variable,defaultValue){
    return(typeof variable!=='undefined')?(variable):(defaultValue);
}

Usage pattern fruit = defaultValue(fruit,'Apple'); 用法模式fruit = defaultValue(fruit,'Apple');

*PS you can rename the defaultValue function to a short name, just don't use default it's a reserved word in javascript. * PS你可以将defaultValue函数重命名为一个简短的名称,只是不要使用default它是javascript中的保留字。


#3楼

Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative 如果传递了OptionalArg,您的逻辑将失败,但计算结果为false - 请尝试将此作为替代方法

if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }

Or an alternative idiom: 或另类成语:

optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;

Use whichever idiom communicates the intent best to you! 使用哪个成语最能传达您的意图!


#4楼

You can use some different schemes for that. 你可以使用一些不同的方案。 I've always tested for arguments.length: 我一直在测试arguments.length:

function myFunc(requiredArg, optionalArg){
  optionalArg = myFunc.arguments.length<2 ? 'defaultValue' : optionalArg;

  ...

-- doing so, it can't possibly fail, but I don't know if your way has any chance of failing, just now I can't think up a scenario, where it actually would fail ... - 这样做,它不可能失败,但我不知道你的方式是否有任何失败的机会,只是现在我想不出一个场景,它实际上会失败...

And then Paul provided one failing scenario !-) 然后保罗提供了一个失败的场景! - )


#5楼

If you need to chuck a literal NULL in, then you could have some issues. 如果你需要在文字中插入NULL ,那么你可能会遇到一些问题。 Apart from that, no, I think you're probably on the right track. 除此之外,不,我认为你可能走在正确的轨道上。

The other method some people choose is taking an assoc array of variables iterating through the argument list. 一些人选择的另一种方法是在参数列表中迭代一组关联变量。 It looks a bit neater but I imagine it's a little (very little) bit more process/memory intensive. 它看起来有点整洁,但我想它有点(很少)更多的进程/内存密集。

function myFunction (argArray) {
    var defaults = {
        'arg1'  :   "value 1",
        'arg2'  :   "value 2",
        'arg3'  :   "value 3",
        'arg4'  :   "value 4"
    }

    for(var i in defaults) 
        if(typeof argArray[i] == "undefined") 
               argArray[i] = defaults[i];

    // ...
}

#6楼

In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration: 在ECMAScript 2015(又名“ES6”)中,您可以在函数声明中声明默认参数值:

function myFunc(requiredArg, optionalArg = 'defaultValue') {
    // do stuff
}

More about them in this article on MDN . 关于MDN的这篇文章中有关它们的更多信息。

This is currently only supported by Firefox , but as the standard has been completed, expect support to improve rapidly. 目前仅支持Firefox ,但随着标准的完成,预计支持将迅速提升。

EDIT (2019-06-12): 编辑(2019-06-12):

Default parameters are now widely supported by modern browsers. 现在,浏览器广泛支持默认参数。 All versions of Internet Explorer do not support this feature. 所有版本的Internet Explorer都不支持此功能。 However, Chrome, Firefox, and Edge currently support it. 但是,Chrome,Firefox和Edge目前支持它。

发布了0 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/p15097962069/article/details/105403037