Confusing Uncaught TypeError: Cannot read property 'n' of undefined only happens when JSON result has a single item, why?

Confusing Uncaught TypeError: Cannot read property 'n' of undefined only happens when JSON result has a single item, why?

我正在通过 YQL 从 RSS 提要中获取 json 数据。当结果数组中有多个项目时,一切都按预期工作。

但是,当结果数组中只有一个项目时,出现以下错误:

Uncaught TypeError: Cannot read property 'content' of undefined

这是根据 json 结果定义变量的相关代码位。错误中引用的 'content' 属性 来自 $isbn 变量,我在其中为结果中的每个项目获取 guid.content

if (data.query.count > 0) {  
  $.each(data.query.results.item, function(i, book) {
    var $title = book.title;
    var $url = book.link;
    var $description = book.description;
    var $isbn = book.guid.content.split(' ', 1);

这是为只有一个结果的 rss 提要返回的 json 数据 JSON Data :

{
  query: {
    count: 1,
    created: "2015-10-01T08:31:51Z",
    lang: "en-US",
    results: {
      item: {
        title: "Hi-5. Sharing stories [videorecording] : Spin me round.",
        link: "http://webpac.sutherlandshire.nsw.gov.au/record=b1252345*eng",
        description: "The big story book is open and Hi-5 are sharing all their story fun with you!",
        guid: {
          isPermaLink: "false",
          content: "9398711204390"
        }
      }
    }
  }
}

然而,当我从包含多个项目的 rss 提要中请求 json 数据时,相同的代码运行得非常好。没有错误,并且定义并使用了 $isbn 变量。

我已经在 Test Case for AJAX fail

设置了一个代码笔来显示这种行为

我明白错误指的是什么,但我不明白为什么它只在 json 数据中有一个项目时产生。

有什么建议吗?

你试过调试吗? http://prntscr.com/8mh030

我认为你错过了输出的缺点,需要改变
$.each(data.query.results.item, function(i, book)

$.each(data.query.results, function(i, book)

在我看来,当返回多个项目时 data.query.results.item 被视为一个数组,但当只返回一个项目时,它被视为一个对象。

这意味着 $.each 正在读取单个项目的所有属性。

解决此问题的一种方法是区别对待单个结果。

if (data.query.count > 0) {  
  $.each(data.query.results.item, function(i, book) {
  var $title = book.title;
  var $url = book.link;
  var $description = book.description;
  var $isbn = book.guid.content.split(' ', 1);
  )};
}else if(data.query.count===1){
  var $title = data.query.results.item.title;
  var $url = data.query.results.item.link;
  var $description = data.query.results.item.description;
  var $isbn = data.query.results.item.guid.content.split(' ', 1);
}