gpt4 book ai didi

javascript - 为什么变量 get 被分配给另一个数组?

转载 作者:行者123 更新时间:2023-12-03 11:53:08 25 4
gpt4 key购买 nike

我正在尝试遍历一个排序数组并计算重复项以创建一个新的摘要数组。

        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] 对象并使用 results[results.length-1].count=1;

将计数添加到该 newCart[i] 对象

关于javascript - 为什么变量 get 被分配给另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25721304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com