gpt4 book ai didi

Javascript变量是一个对象数组,但无法访问元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:13:27 25 4
gpt4 key购买 nike

我正在使用 Firebase 数据库和 Javascript,并且我有代码可以获取每个类别中的每个问题。我有一个名为类别的对象将包含名称、问题和问题计数,然后它将被插入类别列表 (questionsPerCategory)。在回调函数中,我只是执行 console.log(questionsPerCategory)。它打印包含类别和问题的对象(数组)。现在我的问题是,当我执行 console.log(questionsPerCategory[0]) 时说它是 undefined,我还尝试了 console.log(questionsPerCategory.pop( )) 因为它是一个数组,但它也是未定义。这是为什么?下面是控制台日志的代码和图像。补充说明:CODE A和C是异步的,CODE B和D是同步的。

enter image description here

this.getQuestionsForEachCategory = function(callback, questions, questionsPerCategory) {
var ref = firebase.database().ref('category');
var questionRef = firebase.database().ref('question');
console.log('get questions for each category');

// CODE A
ref.once("value", function(snapshot) {

// CODE B
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;

var childData = childSnapshot.val();

var category = {
category_name: childData.category_name
};

// CODE C
questionRef.orderByChild("category_name").equalTo(childData.category_name).once("value", function(questionSnapshot){
var count = 0;
var q = [];

// CODE D
questionSnapshot.forEach(function(childQuestionSnapshot) {
var questionObj = childQuestionSnapshot.val();
count++;

questions.push(questionObj.question);
q.push(questionObj.question);
});

category.questions = q;
category.questionCount = count;
questionsPerCategory.push(category);

});

});
callback(questionsPerCategory);

});
};

最佳答案

回调(questionsPerCategory); 应该在所有async 调用完成时发生。

现在 questionsPerCategory 在调用 callback 时还没有准备好。我会使用 Promise API 来完成此任务。

根据您使用的 Promise 库,这可以通过不同的方式完成,例如通过使用 bluebird看起来你需要 map功能。

关于Javascript变量是一个对象数组,但无法访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39119658/

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