【问题标题】:Object exists but is still undefined in youtube response?对象存在但在 youtube 响应中仍未定义?
【发布时间】:2015-11-02 20:17:39
【问题描述】:

我在使用一些 Youtube API JS 时遇到了一点问题。我已经排查了一段时间,并用 cmets 注释了我的代码,以便您了解问题所在。我知道它们可能是错误的。无论如何感谢您的帮助!

   request.execute(function(response) {
      console.log(response.result.items); // Here you get an array of objects.
      var results = response.result;
      console.log(results.items.length);
      var id = results.items.id;
      for (id in results.items) {

      console.log(results.items.id); // And here it is undedfine. When adding video.Id the console says cannot read property videoId of undefined.
      console.log('if you read this the loop works');
  }
   });

【问题讨论】:

    标签: javascript jquery json youtube-api


    【解决方案1】:

    您正在尝试访问不存在的数组上的id 属性(因此,undefined)。主要问题是 JavaScript 中的 for in 用于迭代对象键,而不是数组。使用常规的for 循环:

    request.execute(function (response) {
      var results = response.result;
      for (var i = 0; i < results.length; i++) {
        console.log(results[i]);
      }
    });
    

    如果不需要支持 IE8,可以使用.forEach()

    (作为旁注,请使用 JavaScript 阅读 for in,因为您的用法有点不正确。)

    【讨论】:

    • 感谢您的帮助,我想您想说的是,即使 ID 对象确实存在,它也无法在 for in 循环中访问,因为它只能进入一个子-降级,因为它使用对象键。
    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多