【问题标题】:Javascript - Is it possible to pass arguments to a function that already has arguments?Javascript - 是否可以将参数传递给已经有参数的函数?
【发布时间】:2021-05-31 12:14:50
【问题描述】:

是否可以向作为参数传递的函数添加参数? 我到达了这个尝试:

function one() {

  const args = Array.prototype.slice.call(arguments);

  const func = args[0];

  const moreArgs = [5]; /// i want number 5 to be arg2

  func.apply(this, moreArgs);

}


function two(arg1, arg2) {
  console.log(arg1);
  console.log(arg2);
}

const call2 = function(){

  return two(3);

}


one(call2)

/// 我得到的输出是:

3

undefined

/// 输出目标:

3

5

这种行为或类似的东西可以在 javascript 中完成吗?

【问题讨论】:

  • 不,您不能将单个参数传递给需要两个参数的函数并期望它神奇地找出第二个参数
  • 也许您正在寻找 bind,而不是:const f = (a, b) => console.log(a, b); const g = f.bind(this, 3); g(5); 产生 3 5.call.apply 立即使用目前已经提供的参数调用该函数。
  • 你的one() 函数是一个非常复杂的(并且不必要的)arguments[0](5)
  • 在您的示例中,您调用one,它使用参数5 调用call2。但是call2 不接受参数。他们什么也没做。你的意思是const call2 = function(arg){ return two(3, arg); }

标签: javascript function arguments


【解决方案1】:

使用two(3, ...arguments); 来实现这样的目标:

function one() {
  const args = Array.prototype.slice.call(arguments);
  const func = args[0];
  const moreArgs = [5];
  func.apply(this, moreArgs);
}


function two(arg1, arg2) {
  console.log(arg1);
  console.log(arg2);
}

const call2 = function(){
  return two(3, ...arguments); // this line was modified
}

one(call2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2011-10-02
    相关资源
    最近更新 更多