以下是修复代码的步骤:

  1. 遍历数组元素:代码中遍历数组使用的是b本身,而应该遍历数组b的每个元素。

  2. 正确计算总需求和总计划:代码中使用了b[j]来计算总需求和总计划,而应该使用当前遍历到的元素item

  3. 在遍历结束后添加数据:代码中在每次遍历时都添加了totalDemandtotalplan,而应该在遍历结束后一次性添加。

以下是修复后的代码:

let b = [{
        'productName': '洋葱500g',
        'pinYin': 'YC',
        'customerName': '广西禾乐生态农业开发有限公司',
        'customerAbbreviation': '平南禾乐',
        'demandCount': 200,
        'realCount': 330,
        'remaks': ''
    },
    {
        'productName': '洋葱500g',
        'pinYin': 'YC',
        'customerName': '广西禾乐生态农业开发有限公司',
        'customerAbbreviation': '平南禾乐',
        'demandCount': 200,
        'realCount': 330,
        'remaks': ''
    },
    {
        'productName': '洋葱500g',
        'pinYin': 'YC',
        'customerName': '广西禾乐生态农业开发有限公司',
        'customerAbbreviation': '平南禾乐',
        'demandCount': 200,
        'realCount': 330,
        'remaks': ''
    }];
let lefttotalDemand, lefttotalplan;

for (let j = 0; j < b.length; j++) {
    let item = b[j];
    if (item !== undefined) {
        lefttotalDemand = item.reduce((pre, cur) => {
            return pre + cur.demandCount;
        }, 0);
        lefttotalplan = item.reduce((pre, cur) => {
            return pre + cur.realCount;
        }, 0);
    }
}

b.forEach(item => {
    item.push({
        totalDemand: lefttotalDemand,
        totalplan: lefttotalplan
    });
});

修复后的代码将每个元素的totalDemandtotalplan计算为整个数组的总需求和总计划,并在遍历完成后将数据添加到每个元素中。

此外,代码中还有其他一些值得注意的地方:

  • 代码中使用item !== undefined来判断元素是否有效,可以进一步优化,例如使用item本身进行判断。
  • 使用reduce方法计算总需求和总计划,代码简洁高效,但需要注意性能问题,对于大型数组,建议使用其他方法。
  • 代码中没有对结果进行输出,建议添加输出语句,方便验证代码逻辑。
JavaScript 代码优化:修复数组遍历和数据添加错误

原文地址: https://www.cveoy.top/t/topic/ndw4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录