调用Kahoot搜索接口后for循环读取card字段为undefined如何解决
问题原因
你出现该问题的核心原因是for...in循环的使用错误:
for...in遍历数组时,得到的迭代变量quiz是数组的下标索引(字符串格式),并不是数组中存储的测验实体对象,字符串本身不存在card属性,所以读取结果为undefined。- 额外注意:
for...in设计初衷是遍历普通对象的可枚举属性,用来遍历数组还可能意外遍历到原型链上的自定义属性,不属于数组遍历的推荐方案。
修复方案
推荐使用for...of直接遍历数组元素,修复后的代码如下:
var options = { 'method': 'GET', 'url': 'https://create.kahoot.it/rest/kahoots/?query='+nam+'&cursor=0&limit=20&topics&grades=&orderBy=relevance&searchCluster=1&includeExtendedCounters=False', 'headers': { 'Authorization': 'Bearer '+token } }; // 发起请求 request(options, function (error, response, body) { if (error) throw new Error(error); var data = JSON.parse(body); var quizzes = data['entities']; console.log(quizzes); // 遍历所有搜索到的测验,用for...of直接拿到每个测验对象 for(const quiz of quizzes) { const card = quiz.card; console.log(card); } });
如果你坚持要使用for...in写法,需要通过索引拿到对应的测验对象:
for(let index in quizzes) { const quiz = quizzes[index]; const card = quiz.card; console.log(card); }
额外优化建议:所有变量尽量用
const/let声明,避免未声明的变量泄漏为全局变量引发其他异常。
内容的提问来源于stack exchange,提问作者Asgwer
相关产品推荐
相关产品推荐

