设置第二个可选参数javascript

时间:2018-07-10 14:02:02

标签: javascript

假设我有一个功能

function myfunction(a, b, c) {
  // do stuff
}

仅使用参数c调用此函数的最佳方法是什么?

a = 1;
b = 2;
c = 'hello';
myfunction(c);

我当时在想:

myfunction(undefined, undefined, c);

但是必须有更好的方法。 我当时想传递一个对象,但是此功能已经被使用,我无法更改参数结构。

5 个答案:

答案 0 :(得分:1)

您可以尝试执行此操作(使用绑定):

a = 1; b = 2; c = 'hello'


function myfunction(a,b,c){
  console.log('a = ', a, 'b = ', b, 'c = ', c);
}

// newFunc same myfunction but first and second parameter is undefined
// potentially incorrect if 'this' is necessary
const newFunc = myfunction.bind(null, undefined, undefined);

newFunc(c);

newFunc(c, 'something');

答案 1 :(得分:1)

最好的方法是按正确的顺序定义参数,因此最后一个是可选参数,然后您将能够使用ES6中定义的可选参数

function(c, a=1, b=2) {
   // ...
}

由于JS不支持命名参数,因此,如果您有许多可选参数,请用单个对象替换它们。

function(obj) {
   // obj.a, obj.b, obj.c
}

或者,您可以在函数正文中使用arguments对象。

function() {
    // arguments[0], arguments[1], arguments[2]
}

如果无法重新设计该功能,请找出参数的默认值,然后使用这些默认值。通常是0,一个空数组或null

答案 2 :(得分:0)

您可以像下面那样使用解构

const a = 1;
const b = 2;
const c = 'hello'

function myfunction(a,b,c){
  console.log(c)
}

function wrapperForMyFunction({a, b, c}){
  return myfunction(a,b,c)
}

wrapperForMyFunction({ c })

另一种方法是创建一个包装器,该包装器将控制您的参数(无需修改功能)

{{1}}

答案 3 :(得分:0)

var a = 1;
var b = 2;
var c = "hello";

myfunction({c:c})

function myfunction(a,b,c){
  if (typeof a === "object") {
      obj = a;
      a = obj.a;
      b = obj.b;
      c = obj.c;
  }
 
  // do stuff
}

这将起作用,但是“ a”永远不能成为对象,这是唯一的问题

答案 4 :(得分:-1)

我认为您正在寻找var args。请看看。

var a = 1; b = 2; c = 'hello'
function varargsFunction1()  
{  
    console.log(arguments[2]);
}    
varargsFunction1(a,b,c); 
相关问题