0

我想向数组中添加 200 多个元素。我想从那个数组中访问它的元素:我有 3 个答案。这 3 个答案需要数组中的元素,但我也不需要 2 个答案中的相同元素。

    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()
    }
}

随机访问元素并将它们分配给答案的最佳方法是什么?

4

1 回答 1

0

使用您的数组长度在良好范围内生成随机索引:

answer1.text = elements[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
于 2013-10-03T12:59:26.143 回答