gpt4 book ai didi

javascript - 购物车实现Javascript。类型错误 : Cannot set property 'id' of undefined

转载 作者:行者123 更新时间:2023-11-28 00:16:50 25 4
gpt4 key购买 nike

我正在尝试实现基本的购物车,但我遇到了一个问题。我需要检查购物车中是否已存在商品,如果存在则增加其数量。但是当我尝试比较 purchases[i].id = this.arr[i].id; 时,它给出了以下错误

TypeError: Cannot set property 'id' of undefined`

购物车代码实现示例:

    var  Cart = {
AddToCart:function(arr,buttonId){
var purchases = [{id: null,name: null,price: null,quantity: 0}];
this.arr = arr;
this.buttonId = buttonId;
for(var i = 0; i <this.arr.length; i++){
if(this.buttonId === this.arr[i].id && purchases[i].id === this.arr[i].id && $("#oredersUL, #" + this.buttonId).length){
purchases[i].quantity++;
console.log(purchases[i]);
}
else {

purchases[i].id = this.arr[i].id;
purchases[i].name = this.arr[i].name;
purchases[i].price = this.arr[i].price;
purchases[i].quantity++;


console.log(purchases);
}

}
}
};

使用示例:

$("#list").delegate("button",'click',function(){
var buttonId = $(this).attr('id');
Cart.AddToCart(phones,buttonId);
});

给定数组:

var phones = [
{
"age": 0,
"id": "motorola-xoom-with-wi-fi",
"imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
"name": "Motorola XOOM\u2122 with Wi-Fi",
"snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb).",
"price": 150
},

最佳答案

您询问是否 purchases[i].id === this.arr[i].idpurchases[i] 尚不存在(甚至尽管 i 可能有其他值)。

首先检查索引i处的元素是否存在:

if (typeof purchases[i] === 'undefined')

现在,如果 purchases[i] 不存在,您需要创建它。我会使用 push 来做到这一点:

purchases.push({
"id": this.arr[i].id,
"name": this.arr[i].name,
"price": this.arr[i].price,
// I have not included "quantity" here because
// what you have right now doesn't make sense:
// purchases[i] doesn't exist
// so the same is true for purchases[i].quantity
});

使用 .push 将意味着您不能信任每个数组元素内容的数组索引(但这可能是一个坏主意 - 这就是为什么您的对象有一个 id )。

这意味着要更新正确的数组元素,您需要执行 something like this 操作(通过id查找数组中的对象)

关于javascript - 购物车实现Javascript。类型错误 : Cannot set property 'id' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30394631/

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