首页 > 解决方案 > Javascript - 是否可以将参数传递给已经有参数的函数?

问题描述

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

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中完成吗?

标签: javascriptfunctionarguments

解决方案


使用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)


推荐阅读