提问者:小点点

在JS中有没有一种方法将特定的参数传递给函数(没有顺序)?[副本]


假设我有以下功能:

function fun(a,b) {
    if(a) {  //condition can be different
        console.log(a);
        // some other code
    }
    if(b) {  //condition can be different
        console.log(b);
        // some other code, not necessary same as above
    }
}

现在我知道可以这样调用上面的函数了:

fun(1,2) // a=1, b=2
fun()    // a=b=undefined
fun(1)   // a=1, b=undefined

但我想做这样的事:

fun(2)   // a=undefined, b=2

我只想传递一个分配给b而不是A的参数。
在C#中可以这样做:

fun(b: 2) // assign b=2

那么在JavaScript中有没有办法做到这一点呢?

我想到的一种方法是
传递一个包含参数的对象,而不是传递两个参数。
如下所示:

function fun(obj) {
    if(obj.a) {
        console.log(obj.a);
        // some other code
    }
    if(obj.b) {
        console.log(obj.b);
        // some other code, not necessary same as above
    }
}

使用上面的方法,我只能传递特定的参数。

但是否有任何方法不包含对函数的任何修改。

注意:-我不想传递null或undefined作为第一个参数,然后传递第二个参数。


共3个答案

匿名用户

这里可以做的是传递一个选项对象作为函数的参数,您可以将AB指定为选项对象的

有几个JavaScript框架使用类似的方法,特别是在构建模块时。

这就是你应该怎么做的功能:

function fun(options) {
    if(options.a) {  //condition can be different
        console.log(options.a);
        // some other code
    }
    if(options.b) {  //condition can be different
        console.log(options.b);
        // some other code, not necessary same as above
    }
}

作为呼叫的示例,您可以执行以下操作:

fun({b: 2})
fun({a:1, b: 3})
fun({a: "a string"})

匿名用户

您可以为此使用closet。这样,您就不必修改原来的函数

null

function fun(a,b) {
    if(a) {  //condition can be different
        console.log(a);
        // some other code
    }
    if(b) {  //condition can be different
        console.log(b);
        // some other code, not necessary same as above
    }
}

function func(a) {
  return function(b) {
    fun(a,b);
  }
}

func()(2);

匿名用户

下面介绍如何在不指定未定义值的情况下实现结果:

null

function fun(obj) {
  console.log(`a=${obj.a}, b=${obj.b}`)
};

fun({b: 2});