Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在带有默认参数的方法中仅提供某些javascript参数_Javascript - Fatal编程技术网

在带有默认参数的方法中仅提供某些javascript参数

在带有默认参数的方法中仅提供某些javascript参数,javascript,Javascript,如果我有这样的方法 函数somethinga,b,c=5,d=10,e=false 我只想提供参数a、b和e,并将其余参数设置为默认值 在python中,我会调用此函数,如下所示: k=a,b,e=True 但是有没有一种等效的方法可以在Javascript中只指定一个默认参数 您必须用未定义的内容填写缺少的内容: 尽管如此,最好重写函数以接收选项参数作为参数: function something(a, b, options) { if (options.c === undefined

如果我有这样的方法 函数somethinga,b,c=5,d=10,e=false 我只想提供参数a、b和e,并将其余参数设置为默认值

在python中,我会调用此函数,如下所示:

k=a,b,e=True


但是有没有一种等效的方法可以在Javascript中只指定一个默认参数

您必须用未定义的内容填写缺少的内容:

尽管如此,最好重写函数以接收选项参数作为参数:

function something(a, b, options) {
    if (options.c === undefined) options.c = 5;
    if (options.d === undefined) options.d = 10;
    if (options.e === undefined) options.e = false;
    // use options.c, options.d and options.e here
    // (give better names to them of course)
}

k = something(a, b, { e: true })
或使用ES6解构分配语法:

function something(a, b, { c=5, d=10, e=false }) {
    // use c, d and e directly here
    // (again, you should give better names to them of course)
}

k = something(a, b, { e: true })
这是在javascript中从Python获取命名参数的常用方法。由于无法像在python中那样直接引用命名参数,因此在JavaScript中,我们通常使用一个选项参数,它是一个简单的对象,很容易内联创建。当您习惯了这种语法后,您将看到它与python中的几乎相同

function something(a, b, { c=5, d=10, e=false }) {
    // use c, d and e directly here
    // (again, you should give better names to them of course)
}

k = something(a, b, { e: true })