0
尝试制作基于网格的问题答案游戏,并使用for循环将文本文件加载到数组中。我想减少冗余代码并使用循环来填充我的数组。我遇到的问题是我的数组在加载函数外丢失/销毁。在加载函数外丢失数组数据
我明白,如果一个数组是在函数内声明的,那么数组自然会在函数退出时被销毁。不过,我在函数之外声明数组,以便在退出函数后数组应保持完整。
我在这里错过了什么?
顺便说一句 - 我没有加载数据的问题。数据加载正确。数据加载完成后,阵列就会被销毁。
//Create the arrays to hold the
//categories, questions, and answers
var categoryArray:Array = new Array();
var quesAnswArray:Array = new Array();
//create the loader
var loader:URLLoader = new URLLoader();
//telling the loader that we are dealing with variables here.
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
//This is an eventlistener, these are used all the time in AS3
//learn to use them, this basically tells flash to listen to a specific event
//and then call a specific function.
//in Our case we listen for the event called COMPLETE which means it will active
//a function called "loading" when our flash movie has completed loading
loader.addEventListener(Event.COMPLETE, loading);
//Here we tell our loading which file to read our categories and questions from.
loader.load(new URLRequest("questions.txt"));
//This is the function that will happen when the eventlistener activates.
//basically it says that our text fields called content_1 and _2's text property
//should be equal to loader.data.var_1 and var_2 (as you might remember from the explanation above).
function loading (event:Event):void{
//loading bar
var total:Number = this.stage.loaderInfo.bytesTotal;
var loaded:Number = this.stage.loaderInfo.bytesLoaded;
bar_mc.scaleX = loaded/total;
loader_txt.text = Math.floor((loaded/total)*100)+ "%";
var varText:URLVariables = new URLVariables(event.target.data);
//populate the category array with the value from the file.
for (var category:int=0; category<13; category++)
{
this["cat"+category] = varText["var_" + [category+1]];
categoryArray.push(this["cat"+category]);
}
//populate the two demensional array of questions and answers.
//columns
for (var cols:int=0; cols<12; cols++){
//rows
for (var rows:int=0; rows<5; rows++){
this["q"+rows] = varText["var_c"+[cols+1]+"q"+[rows+1]];
this["a"+rows] = varText["var_c"+[cols+1]+"a"+[rows+1]];
quesAnswArray.push(new Array());
quesAnswArray[cols].push(this["q"+rows]);
quesAnswArray[cols].push(this["a"+rows]);
}
}
//bonus round q&a
this["finalQ"] = varText["var_c13q1"];
this["finalA"] = varText["var_c13a1"];
quesAnswArray.push(this["finalQ"]);
quesAnswArray.push(this["finalA"]);
if (total == loaded){
play();
this.removeEventListener(Event.ENTER_FRAME, loading);
}
trace(categoryArray); // this traces the array values perfectly
trace(categoryArray.length); // this returns 13 which is correct
}
trace(categoryArray); //this gives me nothing.
trace(categoryArray.length) //gives me 0
就是这样。我只需要让闪存有时间来初始化我的阵列。一旦我做到了,它就像魅力一样。 – Brownarola