Jquery json:未捕获类型错误:无法读取属性'xx'的未定义

Jquery json : Uncaught TypeError: Cannot read property 'xx' of undefined

本文关键字:属性 xx 未定义 读取 json 类型 Jquery 错误      更新时间:2024-04-23

我正在通过JSON检索数据,但问题是我收到了诸如"无法读取未定义的属性'productid'"之类的错误。

JSON文件(data.JSON)

{
    "Products": [
        {
            "productid": "135",
            "productname": "Shirt",
            "productqty": "3",
            "seller_3": "150.00",
            "seller_2": "151.00",
            "seller_7": "153.00",
            "seller_6": "159.00",
            "seller_5": "155.00",
            "seller_1": "157.00",
            "seller_4": "152.00"
        }
    ]
}

执行代码为

var itemQty = 134;
$.getJSON( "../data.json", function(data) {
    if (data.Products.length == 0) {
        /*do nothing*/
    } else if(data.Products.length > 0){
        for (var i = 0; i < data.Products.length; i++) {
            console.log(data.Products[i].productid); // ITS RETURN THE VALUE 135
            if (data.Products[i].productid == itemID) { // <--- ERROR THIS LINE
                if (data.Products[i].productqty == itemQty) {
                    newQuantity = eval(data.Products[i].productqty);
                } else {
                    var newQuantity = eval(itemQty);
                }
                if (newQuantity > options.quantityLimit) {
                    newQuantity = options.quantityLimit
                }
                data.Products[i].productqty = newQuantity;
            } else {
                data.Products.push(cartItem);
            }
        }
    }
}

在console.log中,它返回的值为135,当在IF语句中进行比较时,我得到错误Cannot read property'productid'of undefined。

看起来您正在从循环内部修改产品列表。因此,请仔细查看为cartItem设置值的内容。

  for (var i = 0; i < data.Products.length; i++) {
    ...
    data.Products.push(cartItem);
  }

在迭代列表时,向列表中添加新项是个坏主意。根据itemIDcartItem的设置方式,可能会出现无限循环。尝试在开始循环之前读取.length值一次,这样就不会迭代新项目:

for (var i = 0, len = data.Products.length; i < len; i++) {
  ...
}