如何将变量分配给另一个数组?

时间:2014-09-08 09:39:00

标签: javascript

我试图遍历已排序的数组并计算重复项以创建新的摘要数组。

        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-array中结束?

1 个答案:

答案 0 :(得分:1)

因为当你执行results.push(newCart[i])时,它实际上会将您的购物车对象放入数组中,然后您访问该newCart[i]个对象并使用newCart[i]向该results[results.length-1].count=1个对象添加计数;