// Now go to the random frame // 然后跳到该LABEL播放 gotoAndStop(randomFrame); 而数组包含数据的个数称为长度(length),例如fruitList.length 就等于2 对数组最常用的处理就是从数组中选出有用的数据了,来看一个运用循环的例子: // Create an array 建立数组,里面放了一些歌的类型 var soundtracks = ["electronic", "hip hop", "pop", "alternative", "classical"]; // Check each element to see if it contains "hip hop" // 一个循环,检查每一个元素是否等于"hip hop"这个类型 // 另外,请留意此处MOOCK对FOR的写法,J=0之前有一个VAR,这好象可有可无,其实是一个好习惯! for (var j = 0; j < soundtracks.length; j++) { trace("now examining element: " + j); if (soundtracks[j] == "hip hop") { trace("the location of 'hip hop' is index: " + j); break; // 跳出循环,找到了就不用再找了 } } 关于数组的方法(method) 方法就是从属于某一对象(object)的函数,通常都是对该对象进行处理的函数 好象太抽象了?我们还没讲到什么是对象,其实数组是对象的一种,我们就暂且将数组的方法理解为一个专门处理数组内数据的结构和内容的工具吧 例如一个叫push()的方法就是一个工具,用于为数组添加一个元素,并且加在该数组的最后 使用起来并不复杂,看例子就知: // Create an array with 2 elements var menuItems = ["home", "quit"]; // Add an element 加一个元素 // menuItems becomes ["home", "quit", "products"] // 现在数组的结构变成["home", "quit", "products"] menuItems.push("products"); // Add two more elements 这次是加两个 // menuItems becomes ["home", "quit", "products", "services", "contact"] menuItems.push("services", "contact"); 跟push()相反从最后弹出一个元素的方法是pop() 而跟push()类似,但是是将一个元素加到数组的开头的方法是unshift(),与之相反的是shift() 方法sort和reverse,用于重新排列数组的元素 方法splice用于从数组中间删除某元素 方法slice和concat可以在某些数组的基础上生成另一个新的数组 方法toString和join可以将整个数组变成单一个字符串 以上方法都可以从AS字典里面查到
第十章 第三个版本的选择题
首先,此版本沿用了上一版本的函数answer和gradeUser 在这一版本中,用户的答案与正确答案将使用数组来存放 看看我们的新代码: stop(); // *** Init main timeline variables var displayTotal; // Text field for displaying user's final score var numQuestions = 2; // Number of questions in the quiz var totalCorrect = 0; // Number of correct answers // 上一版本中,用户答案使用了两个变量来存放,但是试想如果是10题、100题呢?使用数组将更容易管理,也更容易处理 var userAnswers = new Array(); // Array containing user's guesses 这是定义数组的语句,但是还未输入数据 var correctAnswers = [3, 2]; // Array containing each correct answer 这一句既定义数组,同时输入数据,因为正确答案是已知的 // *** Function to register the user's answers function answer (choice) { // Tack the user's answer onto our array 将数据PUSH进数组,因为是顺序答题,所以用方法PUSH userAnswers.push(choice); // Do a little navigation, baby // 如果答案数超过题目总数,自然就跳到quizEnd帧了 // 注意在本例中,已经不用上例的answer.currentAnswer而是使用userAnswers.length来控制问题是否结束 // 我们甚至可以用correctAnswers.length来代替numQuestions,记录正确答案数组的长度,不就是题目总数吗? if (userAnswers.length == numQuestions) {