JavaScript中如何根据规则配置动态构造条件判断返回布尔值
多步表单步骤条件显隐判断实现
问题说明
开发多步表单时,需要根据表单字段取值动态决定后续步骤是否展示,接收的条件配置结构示例:
{ cardConditional: { lessThan: 75, show: true, when: "fieldKeyHere" } // 其余步骤配置 }
核心判断逻辑:when指定对应字段的key,支持三类判断规则:
lessThan:字段值小于指定阈值greaterThan:字段值大于指定阈值eq:字段值等于指定值
满足规则时根据show字段决定步骤显隐。
现有代码已经完成了判断符号的字符串映射,但无法将运算符字符串和实际判断逻辑串联,未完成的代码如下:
const checkStepConditional = (step) => { const getMathSymbol = () => { if (step.cardConditional.eq) return "==="; else if (step.cardConditional.lessThan) return "<"; else if (step.cardConditional.greaterThan) return ">"; }; if (step.cardConditional) { const conditionalFieldKey = step.cardConditional.when; return form.values[conditionalFieldKey] // 逻辑卡点位置 } else { return true; } };
实现方案
不要用返回运算符字符串再拼接表达式用eval执行的方案,存在代码注入风险,直接维护「规则类型-判断函数」的映射表即可,逻辑更可控也更安全。
完整可运行代码:
const checkStepConditional = (step) => { // 无特殊配置直接展示步骤 if (!step.cardConditional) return true; const { when, eq, lessThan, greaterThan, show } = step.cardConditional; const currentFieldValue = form.values[when]; // 规则和判断逻辑直接映射,传入阈值返回布尔结果 const checkRuleMap = { eq: (threshold) => currentFieldValue === threshold, lessThan: (threshold) => currentFieldValue < threshold, greaterThan: (threshold) => currentFieldValue > threshold }; let isMatchRule = false; // 判断当前配置命中了哪条规则,注意用!== undefined判断,避免阈值为0、false等假值时判断失效 if (eq !== undefined) { isMatchRule = checkRuleMap.eq(eq); } else if (lessThan !== undefined) { isMatchRule = checkRuleMap.lessThan(lessThan); } else if (greaterThan !== undefined) { isMatchRule = checkRuleMap.greaterThan(greaterThan); } // 结合show配置返回最终显隐结果 return show ? isMatchRule : !isMatchRule; };
方案说明
- 抛弃了原代码中返回运算符字符串的思路,直接把每类规则对应的判断逻辑存在映射对象中,传入配置的阈值就能直接得到判断结果,不需要动态执行代码。
- 规则命中判断使用
!== undefined做校验,兼容阈值为0、false、空字符串这类假值的场景,不会出现配置了规则但判断跳过的问题。 - 补全了配置中
show字段的逻辑:show: true时命中规则展示步骤,show: false时命中规则隐藏步骤,覆盖反向显隐的需求。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

