You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何精简存在大量重复逻辑的JavaScript updateCost函数代码

代码优化方案

完全可以通过配置抽离+公共逻辑复用的方式精简代码,不需要写大量重复的else if分支,核心思路是把不同地块编号对应的个性化参数(上限值mval、扣减额度)统一维护在映射表中,公共计算逻辑只写一次即可。

优化后代码

function updateCost(plotcode) {
    // 特殊逻辑单独处理
    if (plotcode === "KKPP") {
        alert("Fully Invalid!!!");
        KKPP();
        return;
    }

    // 所有地块的参数配置表,新增地块只需在这里加对应配置即可
    const plotConfig = {
        1: { mval: 760, deduct: 10 },
        2: { mval: 760, deduct: 10 },
        3: { mval: 820, deduct: 20 },
        7: { mval: 940, deduct: 40 },
        // 其他地块编号直接在这里补充即可
    };

    // 校验地块编号是否合法
    const config = plotConfig[plotcode];
    if (!config) {
        alert("Invalid Plot Code");
        KKPP();
        return;
    }

    // 公共计算逻辑,仅需写一次
    const pValue = parseInt(localStorage[`plot${plotcode}`]);
    let opValue = 2 * pValue;
    if (opValue >= config.mval) {
        opValue = config.mval;
    }
    const k = localStorage[`plot${plotcode}`] = opValue - config.deduct;

    alert(`Rent of Plot ${plotcode} is updated to ${k}`);
    addtoHistory(`Plot ${plotcode}`, `Rent Updated to ${k}`);
}

方案优势

  • 无重复逻辑:所有计算逻辑统一维护,修改规则只需调整一处
  • 易扩展:新增地块无需新增分支,仅需在plotConfig中添加对应编号的参数即可
  • 可读性更高:所有地块参数一目了然,排查参数错误不需要遍历大量分支

内容的提问来源于stack exchange,提问作者Random Kindle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:48:05