javascript - 在我的 JS 代码中找不到错误

标签 javascript arrays

我正在尝试创建一个最终数组,该数组保存带有月份的对象的总和,并合并相同的月份并对它们的 itemCount 求和。

Z 数组来自 Chrome 的控制台:

0: Object
itemCount: 6
month: "Aug"

1: Object
itemCount: 0
month: "Jun"

2: Object
itemCount: 0
month: "Sep"

3: Object
itemCount: 0
month: "Sep"    

以及我编写的代码,用于按月对 itemCount 求和,如果有相同的月份则合并:

let counterCurrItem = 0, month, 
        finalArr = [], itemCount = 0

    for (i = 0; i < Z.length; i++) {
        month = Z[i].month
        itemCount = Z[i].itemCount
        if (Z[i + 1] !== undefined) {
            if (month == Z[i + 1].month) {
                counterCurrItem = counterCurrItem + itemCount
            } else {
                finalArr.push([counterCurrItem, month])
            }
        } else {
            finalArr.push([counterCurrItem, month])
        }
    }

但是最终数组没有包含预期值,我希望它的第一个数组为 [6, 'Aug'] 但它是 [0, 'Aug']。

那么我的代码哪里出了问题?

一些注意事项:月份总是按字母顺序排序,Z 数组中总是有超过 1 个对象。

最佳答案

你像这样添加项目 finalArr.push([counterCurrItem, month]) 但变量 counterCurrItem 被添加到 if 语句中,所以它永远不会增加;

此外,您应该在循环中而不是在循环外创建一个临时变量,这样您就不会得到不正确的数据。

做最少的改变:

let counterCurrItem = 0, month, 
    finalArr = [], itemCount = 0

for (i = 0; i < Z.length; i++) {
    month = Z[i].month
    itemCount = Z[i].itemCount
    if (Z[i + 1] && month == Z[i + 1].month ) {
        counterCurrItem = counterCurrItem + itemCount
        finalArr.push([counterCurrItem, month])
    } else {
        finalArr.push([itemCount, month])
    }
}

关于javascript - 在我的 JS 代码中找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34438455/

相关文章:

javascript - Mobx:向可观察对象添加新的(数组)属性

javascript - 如何使用 javascript 获取学年

javascript - Javascript 中数字加数字为 NaN

javascript - 在 Plotly.js 中的条形之间放置刻度线

javascript - `before()` 和 `beforeEach()` 有什么区别?

php - 仅在需要时初始化数组中的变量

arrays - 如何在 DTrace 中打印关联数组?

php - 使用 StdClass 对象为多维数组创建 foreach 循环时遇到问题

c - 自由释放对象的校验和不正确 - C 中的二维 double 组

java - 三维数组以错误的顺序到达串行端口