在多个文本字段中显示随机排序的数组

时间:2014-07-26 20:31:05

标签: actionscript-3

我有一个随机排序的数组,例如3个项目。我不想在一个动态文本框中显示所有3个项目(请参阅下面的代码),而是希望在3个不同的文本框中显示每个项目。我该怎么做呢?

var Questions:Array = new Array;

Questions[0] = "<b><p>Where Were You Born?</p><br/>";
Questions[1] = "<b><p>What is Your Name?</p><br/>";
Questions[2] = "<b><p>When is Your Birthday?</p><br/>";

function randomize (a:*, b:*): int {
    return (Math.random() > .5) ? 1: -1;
}

questions_txtbox.htmlText = Questions.toString() && Questions.join("");

1 个答案:

答案 0 :(得分:1)

以下代码完成了您的要求,虽然洗牌功能很粗糙,但它可以完成工作。我还动态生成了三个文本字段,而不是在舞台上创建它们并为它们提供唯一的实例名称,因此您需要根据需要调整这些新文本字段的x / y坐标。我在Flash CC 2014上对此进行了测试,并且运行正常。

import flash.text.TextField;

var Questions:Array = new Array();
Questions[0] = "<b><p>Where Were You Born?</p><br/>";
Questions[1] = "<b><p>What is Your Name?</p><br/>";
Questions[2] = "<b><p>When is Your Birthday?</p><br/>";
var shuffleAttempts:int = 10 * Questions.length;
var questionTextFields:Array = new Array(3);

function randomize (a:*, b:*): int {
    return (Math.random() > .5) ? 1: -1;
}

function shuffleQuestions(arr:Array):void {
    var temp:String;
    for(var i:int = 0; i < shuffleAttempts; i++ ) {
        var randIndex1:int = Math.floor(Math.random() * Questions.length);
        var randIndex2:int = Math.floor(Math.random() * Questions.length);

        if( randIndex1 != randIndex2 ) {
            temp = Questions[randIndex1];
            Questions[randIndex1] = Questions[randIndex2];
            Questions[randIndex2] = temp;
        }

    }
}
shuffleQuestions(Questions);    // shuffle question list

for( var questionIndex:int = 0; questionIndex < 3; questionIndex++ ) {
    if( questionIndex < Questions.length ) {

        var questionField = new TextField(); // create new text field
        questionField.htmlText = Questions[questionIndex]; // take a question from the questions list and set the text fields text property
        questionField.y = questionIndex * 20;   // move the text field so that it does not overlap another text field
        questionField.autoSize = "left";    // autosize the text field to ensure all the text is readable

        questionTextFields[questionIndex] = questionField;   // store reference to question textfield instance in array for later use.

        addChild(questionField);   // add textfield to stage
    }
}