对象存在但在 youtube 响应中仍未定义?

Object exists but is still undefined in youtube response?

我在使用 Youtube API JS 时遇到了一些问题。我已经排除了一段时间的故障,并且用注释对我的代码进行了注释,以便您了解问题所在。我知道他们有几件不同的事情可能是错误的。无论如何,感谢您的帮助!

   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');
  }
   });

您正在尝试访问数组上的 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().

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