我正在尝试创建一个最终数组,该数组保存带有月份的对象的总和,并合并相同的月份并对它们的 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/