.each 长度给出 undefined

.each length gives undefined

我的 if 陈述有什么问题? else 有效,但 if 无效。count1 给出 undefinedif 语句中的术语在其他地方也适用,所以这不是问题。

$.ajax({
  type: 'GET',
  url: '/api/Carts',
  dataType: 'json',
  headers: {
    'Authorization': 'Bearer ' + localStorage.getItem('accessToken')
  },
  success: function(data) {
    $.each(data, function(index, val) {
      if (val.CompanyID == JSON.parse(localStorage.getItem('userName')) && val.IsInCart == true) {
        var count1 = val.length;
        console.log('Shopping cart has ' + count1);
      } else {
        var count = data.length;
        console.log('Shopping cart has ' + count);
      }
    });
  }
})

看起来 data 包含购物车中的商品?在这种情况下,val 是每个项目。

您需要确保 val 也是一个数组,或者,如果这不可行,您需要确保它有一个 属性 来存储您要访问的值正在寻找 count1.

的分配值

我建议只评估 data 的长度,因为它包含购物车中的商品(见下文)。这意味着您不需要 else 除非您想要一条消息说“您的购物车是空的”或其他内容。

无关:我建议您可以使代码更简洁一些。

我已经更改了您的代码以同时清理 if 语句:

$.ajax({
  type: 'GET',
  url: '/api/Carts',
  dataType: 'json',
  headers: {
    'Authorization': 'Bearer ' + localStorage.getItem('accessToken')
  },
  success: function(data) {
    $.each(data, function(index, val) {
      let uname = JSON.parse(localStorage.getItem('userName'));
      if (val.CompanyID == uname && val.IsInCart == true) {
        var count1 = data.length;
        console.log('Shopping cart has ' + count1);
      }
    });
  }
})

HTH

编辑 1

根据您的评论:

.each() 给你一个项目 (val),它不能给你多个项目。因此,由于看起来您正在尝试输出购物车中的商品数量,因此您可能想要的是这样的:

$.ajax({
  type: 'GET',
  url: '/api/Carts',
  dataType: 'json',
  headers: {
    'Authorization': 'Bearer ' + localStorage.getItem('accessToken')
  },
  success: function(data) {
    // Get number of items.
    let count = data.length;
    console.log('Shopping car thas ' + count);

    // Get details about each item.
    $.each(data, function(index, val) {
      let uname = JSON.parse(localStorage.getItem('userName'));
      if (val.CompanyID == uname && val.IsInCart == true) {
        console.log('This item is a ' + val.Name); // Example.
      }
    });
  }
})