2013-10-03 60 views
0

我想將200多個元素添加到數組中。 從這個數組中,我想訪問它的元素: 我有3個答案。這3個答案需要數組中的元素,但我也不需要2個答案中的相同元素。如何在AS3的測驗中正確地訪問數組?

var random: Number; 
var answ: Array = [var1, var2, var3]; 
    var elements : Array = [1,2,3,4,5,6,7,8,9,...]; 
GAME.answer1.addEventListener(MouseEvent.CLICK, randomNumberEvent); 
    GAME.answer2.addEventListener(MouseEvent.CLICK, randomNumberEvent); 
    GAME.answer3.addEventListener(MouseEvent.CLICK, randomNumberEvent); 
answer1.text = elements[random]; 
answer2.text = elements[random]; 
answer3.text = elements[random]; 
function displayRandomNumber() 
{ 
randomGen = randBetween(2, 120); 
GAME.randomNumberText.text = randomGen.toString(); 
if(myArray.indexOf(randomGen) == -1){ 
myArray.push(randomGen); 
cookie.data.storedmyArray=myArray; 
cookie.flush(); 
levelu = randomGen; 
}else{ 
displayRandomNumber() 
    } 
} 

隨機訪問元素並將其分配給答案的最佳方法是什麼?

回答

0

使用您的陣列長度以在良好的範圍內的隨機索引:

answer1.text =元素[INT(的Math.random()* elements.length)];

如果你想避免雙重條目:

package 
{ 
    import flash.display.Sprite; 

    public class TestAnswer extends Sprite 
    { 
     public function TestAnswer() 
     { 
      super(); 

      var answers : Array = ["A","B","C","D","E","F","G","H","I","J","K"]; 

      for(var i : uint = 0; i < 10; ++i) 
       trace(getAnswers(3, answers)); 
     } 

     public function getAnswers(num : uint, from : Array) : Array 
     { 
      if(num > from.length) 
       throw new Error("Not enought answers provided"); 

      var result : Array = []; 

      // Clone Array 
      var newArray : Array = from.concat(); 

      // Extract random answers 
      while(result.length != num) 
       result = result.concat(newArray.splice(int(newArray.length * Math.random()), 1)); 

      return result; 
     } 
    } 
} 

輸出爲例:

A,C,D 
A,G,J 
F,E,J 
I,A,C 
H,K,C 
I,H,K 
D,F,A 
I,G,A 
A,H,J 
D,I,H 
+0

THX非常本 –