You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

JavaScript相似变量重构为for循环:变量引用错误求助

解决变量名映射问题,简化重复的Input创建代码

你遇到的核心问题是无法通过字符串拼接的方式直接引用局部变量——tableColumnData[j] +"Data"只会生成一个字符串(比如"monthActualData"),而不是获取同名变量的实际值。这里推荐用对象映射的方式来解决,既清晰又避免了不安全的eval操作。

具体修改思路:

  1. 在创建完各个数据变量后,把它们存入一个对象,用你数组里的前缀作为键名,对应的数据作为值
  2. 遍历前缀数组时,直接从这个映射对象里取出对应的数据赋值给temp.value

修改后的完整代码:

var fullForm = document.createElement('form');
fullForm.action = '/fpdf/requests/print_fullreport.php?year=' + requestYear + '&month=' + getMonth(requestMonth);
fullForm.id = 'fullForm';
fullForm.target = '_blank';
fullForm.method = 'post';

var showrooms = [1, 3, 4, 24, 27, 29, 34, 36, 37, 8, 21, 25, 26, 28, 31, 33, -1];

for (var i = 0; i < showrooms.length; i++) {
    var showroomData = allTargetsData.monthlyDetail[showrooms[i]];
    var currencyData = showroomData.currency;
    var showroomname = showroomData.showroom_name;
    
    var monthActualData = showroomData.total;
    var monthTargetData = Math.round(allTargetsData.originalTarget[requestYear][showrooms[i]][requestMonth]['amount']);
    var priorYearData = allTargetsData.realFigure[requestYear - 1][showrooms[i]]['figures'][requestMonth];
    var priorYearToDateData = showroomData.ly_ytd;
    var yearToDateTargetData = Math.round(showroomData.ytd_target);
    var yearToDateActualData = showroomData.ytd;
    
    var calculation1 = (showroomData.ytd - showroomData.ly_ytd).toFixed(2);
    var YTDVsPYTDSalesCurrencyData = calculation1;
    var calculation2 = (parseFloat(showroomData.ytd - showroomData.ly_ytd)/showroomData.ly_ytd).toFixed(2);
    var YTDVsPYTDSalesinPercentData = (calculation2*100);
    if (isNaN(YTDVsPYTDSalesinPercentData) || YTDVsPYTDSalesinPercentData == "Infinity"){
        YTDVsPYTDSalesinPercentData = 0;
    }
    
    var calculation3 = (showroomData.ytd - showroomData.ytd_target).toFixed(2);
    var YTDVsYTDTargetinSalesCurrencyData = (calculation3*100)/100;
    var calculation4 = (parseFloat(showroomData.ytd - showroomData.ytd_target)/parseFloat(showroomData.ytd_target)).toFixed(2);
    var YTDVsYTDTargetinPercentData = calculation4*100;
    if (isNaN(YTDVsYTDTargetinPercentData) || YTDVsYTDTargetinPercentData == "Infinity"){
        YTDVsYTDTargetinPercentData = 0;
    }
    
    var showroomCurrency = document.createElement('input');
    showroomCurrency.name = "showroomCurrency_" + showrooms[i];
    showroomCurrency.value = currencyData;
    fullForm.appendChild(showroomCurrency);
    
    var showroomNameField = document.createElement('input');
    showroomNameField.name = "showroomname_" + showrooms[i];
    showroomNameField.value = showroomname;
    fullForm.appendChild(showroomNameField);
    
    // 关键:创建数据映射对象,关联前缀和对应的数据
    var dataMap = {
        monthActual: monthActualData,
        monthTarget: monthTargetData,
        priorYear: priorYearData,
        priorYearToDate: priorYearToDateData,
        yearToDateTarget: yearToDateTargetData,
        yearToDateActual: yearToDateActualData,
        YTDVsPYTDSalesCurrency: YTDVsPYTDSalesCurrencyData,
        YTDVsPYTDSalesinPercent: YTDVsPYTDSalesinPercentData,
        YTDVsYTDTargetinSalesCurrency: YTDVsYTDTargetinSalesCurrencyData,
        YTDVsYTDTargetinPercent: YTDVsYTDTargetinPercentData
    };
    
    // 直接用对象的键作为遍历数组,避免重复维护两个列表
    var tableColumnData = Object.keys(dataMap);
    for(var j=0; j<tableColumnData.length; j++){
        var key = tableColumnData[j];
        var temp = document.createElement('input');
        temp.name = key + "_" + showrooms[i];
        temp.value = dataMap[key]; // 从映射对象中获取实际数据值
        fullForm.appendChild(temp);
    }
}

这个方案的优势:

  • 避开了eval这类不安全的操作(eval会执行字符串代码,容易引发安全隐患和调试困难)
  • 数据映射对象让变量关系更直观,后续新增字段时只需在dataMap里添加键值对,不用同时修改数组,减少出错概率
  • 完全遵循DRY(Don't Repeat Yourself)原则,代码结构更简洁易维护

内容的提问来源于stack exchange,提问作者hello world

火山引擎 最新活动