JavaScript如何根据条件动态传参避免重复调用函数
问题描述
我定义了如下名为func的函数:
const otherFunc = (arg1, arg2) => {...} const func = (condition1, condition2) => { condition1 || condition2 ? otherFunc(value, true) : otherFunc(false) }
上述写法可以正常运行,但我希望找到一种方案,避免重复书写两次otherFunc调用语句。我曾尝试如下写法,但存在语法错误无法正常运行:
const func = (condition1, condition2) => { otherFunc((condition1 || condition2) && ...[value, true]) }
补充说明:我实现该逻辑的目的是编写一个支持链式调用if、else逻辑的工具函数,对应实现代码如下:
function is(value, done) { return { else: (v) => is(done ? value : v, done), if: (condition) => (done || condition ? is(value, true) : is(null)), get: value, }; } const n = 50000; console.log( is('small') .if(n < 1000) .else('big') .if(n > 10000) .else('medium-big') .if(n > 5000) .else('medium-small').get, );
核心诉求:如何正确实现根据条件动态传递不同参数,仅书写一次函数调用即可满足需求?
解决方案
你之前的写法报错,本质是对展开运算符的使用场景理解有偏差:展开运算符不能直接接在逻辑表达式的结果后使用,它必须作为函数传参列表、数组/对象字面量的直接组成部分存在。
最简洁的实现方式是用三元表达式先根据条件返回对应的参数数组,再统一对数组做展开传入函数,全程只需要调用一次otherFunc:
const func = (condition1, condition2) => { otherFunc(...(condition1 || condition2 ? [value, true] : [false])) }
这段代码和你最初的写法逻辑完全等价:
- 条件满足时,展开
[value, true],实际执行otherFunc(value, true) - 条件不满足时,展开
[false],实际执行otherFunc(false),第二个形参接收到undefined,和原逻辑行为完全一致
如果后续需要调整参数,只需要修改对应数组内的元素即可,不需要重复修改函数调用语句,可维护性更高。
你写的链式if/else工具本身逻辑可正常运行,如果后续需要在链式逻辑里加动态传参的逻辑,也可以套用这个「先组装参数数组,再统一展开传参」的思路实现。
内容的提问来源于stack exchange,提问作者Guido Glielmi
相关产品推荐
相关产品推荐

