【问题标题】:Tracing and storing an array (AS3)跟踪和存储数组 (AS3)
【发布时间】:2014-08-02 14:49:21
【问题描述】:

我有一个数组,其中使用列表响应记录每个问题的响应。 for 循环,一旦到达数组中的最后一个问题,就会显示另一个按钮(标题为“继续”)。一个人单击这个现在可见的按钮以继续任务。我的代码中有两个跟踪命令,一个在 for 循环中,一个在单击继续按钮时的 for 中。 for 循环中的跟踪功能有效;但是,单击继续按钮时在函数中执行的跟踪返回“未定义”值。 (如果我的描述不清楚,我将使用下面的代码使其更具体。)

我的问题是为什么被跟踪的完全相同的值会在一个实例中返回值而不是另一个?我的目标是将数组中问题的响应存储到字符串中。

var listOfQuestions:Array = new Array;
var listOfAnswers:Array = new Array;
var i:int = 0;

listOfQuestions[0] = "Question 1";
listOfQuestions[1] = "Question 2";
listOfQuestions[2] = "Question 3";


lstResponses.addItem({label: "Response 1", data: "1"});
lstResponses.addItem({label: "Response 2", data: "2"});
lstResponses.addItem({label: "Response 3", data: "3"});

btnNextQuestion.addEventListener(MouseEvent.CLICK, presentNextQuestion);  

function presentNextQuestion(evt:MouseEvent){
    listOfAnswers[i] = lstResponses.selectedItem.data;
    lstResponses.selectedItem = null;
    i++;

    //Present the element stored in index “i”;
    if(i == listOfQuestions.length)
    {
        txtQuestion.htmlText = "<b>End of list. Click the Continue to Part II for the next part.</b>", btnContinue.visible = true, btnNextQuestion.visible = false;
        //Output all the questions and answers;
        for (i = 0; i <listOfQuestions.length; i++)
        {
        trace(i, listOfQuestions[i], listOfAnswers[i]);
        }
    }
    /*If there are more elements left, present the element stored in index “i.”*/
    else
    {
        txtQuestion.htmlText = listOfQuestions[i];
    }
}

btnContinue.addEventListener(MouseEvent.CLICK, continueClicked);
function continueClicked(evt:MouseEvent){
    trace(listOfAnswers[i]);
}

使用上面的代码重申我的问题:

 trace(i, listOfQuestions[i], listOfAnswers[i])

产生预期结果,即 0 Question 1 [response]。然而,

trace(listOfAnswers[i]);

在代码的最后一行产生“未定义”。

我还想知道这个错误是否是由于需要将数据转换为字符串。在这方面,我添加了以下代码(见下文),但我收到的错误是:错误 #1010: A term is undefined and has no properties。

var b:String = new String;
b = listOfAnswers[i].toString()
b = listOfAnswers[i].join("");

感谢您的时间和耐心。

【问题讨论】:

    标签: arrays actionscript-3


    【解决方案1】:

    问题似乎是当您单击“继续”按钮时如何跟踪答案。您正在 i 的索引处跟踪答案,但您的代码不会阻止 i 增加超过您的列表长度。

    我的猜测是您正在单击下一步按钮,直到它告诉您已到达列表末尾,然后您才单击继续按钮。如果是这样,i 将是 3,而您正在尝试追踪 listOfAnswers [3],这比您的列表长度多一个,给您undefined

    尝试替换

    trace(listOfAnswers[i]);
    

    for (i = 0; i <listOfQuestions.length; i++)
    {
        trace(listOfAnswers[i]);
    }
    

    【讨论】:

    • 感谢您的评论。你的假设都是正确的。我实现了你的代码;但是,现在正在对响应列表进行三次跟踪。 (我希望它只被追踪一次。)
    • 嗯。似乎即使响应被重复/跟踪 3 次(因为数组中有三个项目),如果您再次访问该信息,它只会显示一次(即,其他 2 个重复项未显示,即好的)。因此,即时输出将数据显示 3 次这一事实只是一个小小的不便。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2018-03-01
    相关资源
    最近更新 更多