gpt4 book ai didi

javascript - 对象存在,但在 YouTube 响应中仍未定义?

转载 作者:行者123 更新时间:2023-11-28 19:04:45 38 4
gpt4 key购买 nike

我在使用某些 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()

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

关于javascript - 对象存在,但在 YouTube 响应中仍未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31927657/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com