我正在尝试遍历一个排序的数组并计算重复项以创建一个新的摘要数组。
for (var i = 0; i < newCart.length; i++) {
//if new item.
console.log(JSON.stringify(newCart[i - 1]))
if ( JSON.stringify(newCart[i - 1]) !== JSON.stringify(newCart[i])) {
//add to new displayed items in cart
results.push(newCart[i]);
results[results.length - 1].count = 1
}else{
console.log('second')
//add one to the count.
results[results.length - 1].count++;
}
}
当我遍历三个项目时,得到以下输出:
undefined
{"id":1,"name":"Skateboard","price":1299,"currency":"SEK","image":"/static/img/products/1.jpg","thumbnail":"/static/img/products/1-t.jpg","description":"This board is the boss!","count":1} main.js:47
{"id":1,"name":"Skateboard","price":1299,"currency":"SEK","image":"/static/img/products/1.jpg","thumbnail":"/static/img/products/1-t.jpg","description":"This board is the boss!","count":1}
count变量怎么可能最终出现在newCart数组中?
最佳答案
因为当您执行results.push(newCart[i])
时,实际上会将购物车对象放入数组中,然后您访问该newCart[i]
对象,并使用newCart[i]
将计数添加到该results[results.length-1].count=1
对象中;