代码中存在以下问题:

  1. 在for循环中,应该遍历数组b的每个元素,而不是b本身,即应该改为:
for (let j = 0; j < b.length; j++) {
    let item = b[j];
    // ...
}
  1. 在计算lefttotalDemand和lefttotalplan时,应该使用item而不是b[j],即应该改为:
lefttotalDemand = item.reduce((pre, cur) => {
    return pre + cur.demandCount;
}, 0);
lefttotalplan = item.reduce((pre, cur) => {
    return pre + cur.realCount;
}, 0);
  1. 在给每个元素添加totalDemand和totalplan时,应该在遍历完每个元素后添加,而不是在每次遍历时都添加,即应该将添加代码移出循环:
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
    });
});
let b = productName 洋葱500g pinYin YC customerName 广西禾乐生态农业开发有限公司 customerAbbreviation 平南禾乐 demandCount 200 realCount 330 remaks product

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

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