Adobe Acrobat X中PDF JavaScript条件语句语法错误及油炸机油耗年成本计算求助
Adobe Acrobat X中PDF JavaScript条件语句语法错误及油炸机油耗年成本计算求助
你好呀!第一次写PDF表单的JavaScript计算代码遇到问题很正常,我帮你梳理下代码里的错误,再给出修正后的版本:
代码里的核心问题
- 相等比较符用错了:JavaScript里判断两个值相等要用
==(松散相等)或者===(严格相等),你用的单个=是赋值操作符,这会同时导致语法错误和逻辑偏差。 - 条件括号未闭合:每个
else if的条件语句末尾都少了一个闭合的),比如else if ((this.getField("Single Fryer").value) = "MJ140" {这行,条件部分的右括号缺失,直接触发了语法报错。
修正后的完整代码
if ((this.getField("Single Fryer").value) === "MJ150") { event.value = (this.getField("No. of Units").value) * (this.getField("Oil Cost").value) * (this.getField("Oil Changes per Week").value) * 25 * 52 } else if ((this.getField("Single Fryer").value) === "MJ140") { event.value = (this.getField("No. of Units").value) * (this.getField("Oil Cost").value) * (this.getField("Oil Changes per Week").value) * 20 * 52 } else if ((this.getField("Single Fryer").value) === "SR42") { event.value = (this.getField("No. of Units").value) * (this.getField("Oil Cost").value) * (this.getField("Oil Changes per Week").value) * 20 * 52 } else if ((this.getField("Single Fryer").value) === "RE114") { event.value = (this.getField("No. of Units").value) * (this.getField("Oil Cost").value) * (this.getField("Oil Changes per Week").value) * 20 * 52 } else if ((this.getField("Single Fryer").value) === "RE117") { event.value = (this.getField("No. of Units").value) * (this.getField("Oil Cost").value) * (this.getField("Oil Changes per Week").value) * 20 * 52 } else { event.value = "N/A" }
额外的代码优化建议
你会发现除了MJ150对应的系数是25,其他几个型号的系数都是20,我们可以简化代码减少冗余,后期维护型号也更方便:
// 先把需要重复获取的字段值存起来,提升代码可读性 const fryerType = this.getField("Single Fryer").value; const unitCount = this.getField("No. of Units").value; const costPerOil = this.getField("Oil Cost").value; const weeklyChanges = this.getField("Oil Changes per Week").value; let volumeMultiplier; // 批量判断同系数的型号 if (fryerType === "MJ150") { volumeMultiplier = 25; } else if (["MJ140", "SR42", "RE114", "RE117"].includes(fryerType)) { volumeMultiplier = 20; } else { event.value = "N/A"; return; // 提前退出,避免无效计算 } // 统一计算逻辑 event.value = unitCount * costPerOil * weeklyChanges * volumeMultiplier * 52;
验证你的预期结果
按照你给出的输入参数:
- No. of Units = 4
- Oil Cost ($/L) = 4
- Oil Changes per Week = 3
- Single Fryer = MJ150
计算逻辑为 4 * 4 * 3 * 25 * 52 = 62400,修正后的代码运行后就能得到你期望的结果啦!
备注:内容来源于stack exchange,提问作者SupOnly
相关产品推荐
相关产品推荐

