我有两个功能:
first - takes 1 argument
secon - takes 2 arguments然后我有第三个函数,它接收一个函数和一个值作为参数。
我不知道如何让第三个函数知道它正在接收一个参数还是两个参数,这取决于在第二个参数中传递的是哪个函数?
**在下面的示例中,当调用third时,在代码末尾的两个调用中都应该返回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)));
发布于 2020-06-10 05:11:32
看起来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));
https://stackoverflow.com/questions/62291754
复制相似问题