【问题标题】:Passing function to a function and varying length arguments将函数传递给函数和不同长度的参数
【发布时间】:2020-06-09 20:59:46
【问题描述】:

我有两个功能:

first - takes 1 argument
secon - takes 2 arguments

然后我有第三个函数,它接收一个函数和一个值作为参数。

我无法弄清楚如何让第三个函数知道它正在接收一个参数或两个参数,具体取决于在第二个参数中传递的函数???

**在下面的示例中,当调用第三个时,它应该在代码末尾的两个调用中返回 2。

let val = 12;

let val2 = 14
let toC = 14;

// checks if val === 12 | takes 1 argument
const first = num => num === 12 ?2 :0;

// checks if val === toC | takes 2 arguments
const second = (num, check) => num === check ?2 :0;

// third function that receives a function and a val as arguments
const third = (func, num) => {
  let temp = func(num);
  return temp;
}

// this one works
console.log(third(first, val));

// this doesn't
console.log(third(second, (val2, toC)));

【问题讨论】:

    标签: javascript function arguments


    【解决方案1】:

    看起来third 函数只是为了调用作为参数提供的函数并返回值。在这种情况下,您可以使用rest parameters

    let val = 12;
    
    let val2 = 14
    let toC = 14;
    
    // checks if val === 12 | takes 1 argument
    const first = num => num === 12 ? 2 :0;
    
    // checks if val === toC | takes 2 arguments
    const second = (num, check) => num === check ?2 :0;
    
    const third = (func, ...args) => {
      let temp = func(...args);
      return temp;
    }
    
    
    console.log(third(first, val));
    
    console.log(third(second, val2, toC));

    【讨论】:

    • 哈哈哈!!我知道这是一件简单明了的事。一直在使用传播运算符和参数!谢谢谢谢!
    • 我很高兴它有帮助。
    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多