【问题标题】:Shoping cart realization Javascript. TypeError: Cannot set property 'id' of undefined购物车实现Javascript。 TypeError:无法设置未定义的属性“id”
【发布时间】:2015-05-22 19:28:43
【问题描述】:

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

TypeError: 无法设置未定义的属性 'id'

购物车代码实现示例:

    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
    },

【问题讨论】:

  • 如果你 console.log(arr) 就在产生错误的那一行之前,你会得到什么?
  • 您对 purchasesarr 使用相同的索引,尽管您没有测试 ``purchases[i]` 是 null
  • @RoryMcCrossan 它给了我位置 i 的数组:[Object]0: Objectid: "motorola-xoom-with-wi-fi"name: "Motorola XOOM™ with Wi-Fi"price: 150quantity: 1__proto__: Objectlength: 1__proto__: Array[0]

标签: javascript jquery arrays


【解决方案1】:

您问的是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 在数组中查找对象)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    相关资源
    最近更新 更多